I have a stored procedure which generates and executes a piece of dynamic T-SQL which, once built up, looks like this
SELECT
tblUsers.strUserName AS [Username]
,tblUsers.strEmail AS [Email]
,tblUserAuditLog.strIpAddress AS [IP Address]
,tblUserAuditLog.dtAuditTimeStamp AS [Timestamp]
,tblUserAuditLog.strAuditLogAction AS [Action]
,tblUserAuditLog.strLogDetails AS [Details]
FROM
tblUserAuditLog
LEFT OUTER JOIN tblUsers
ON tblUserAuditLog.intUserIdFK = tblUsers.intUserId
WHERE
tblUsers.strUserName = 'a12jun'
AND tblUserAuditLog.dtAuditTimeStamp >= '2012-08-10'
This query can return several thousand rows in the dev environment and will return considerably more in live.
I want to find out how many rows the dynamic query returns before I actually return the results, so that if the number is more than some limit, I can return a 'narrow your query' error message.
I have tried generating another piece of SQL like this:
DECLARE @sqlrowcount NVARCHAR(MAX);
SET @sqlrowcount = 'SELECT COUNT(*) FROM (' + @sql + ') AS TEMP';
EXEC(@sqlrowcount);
IF @@ROWCOUNT > @limit BEGIN .... END
where @sql
is the dynamic query. I then embarrassingly realised that EXEC(@sqlrowcount)
will always return 1
, because it returns one record whose value is the number of records.
Is there a (relatively) elegant way of doing this, e.g. without writing the result to a temporary table?