I have a stored procedure that generates and executes a piece of dynamic T-SQL, which after creating it 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 significantly more in live mode.
I want to know how many lines a dynamic query returns before I return the results, so if the number is greater than a certain limit, I can return the error โnarrow your queryโ.
I tried to create another SQL fragment:
DECLARE @sqlrowcount NVARCHAR(MAX); SET @sqlrowcount = 'SELECT COUNT(*) FROM (' + @sql + ') AS TEMP'; EXEC(@sqlrowcount); IF @@ROWCOUNT > @limit BEGIN .... END
where @sql is a dynamic query. Then I confusedly realized that EXEC(@sqlrowcount) will always return 1 because it returns a single record whose value is the number of records.
There is a (relatively) elegant way to do this, for example. without writing the result to the temporary table?
Arj
source share