我有一个存储过程,它生成并执行一段动态 T-SQL,一旦建立起来,看起来像这样
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'
此查询可以在开发环境中返回数千行,并且会在实时返回更多。
我想在实际返回结果之前找出动态查询返回的行数,这样如果数量超过某个限制,我可以返回“缩小查询”错误消息。
我试过生成另一段这样的 SQL:
DECLARE @sqlrowcount NVARCHAR(MAX);
SET @sqlrowcount = 'SELECT COUNT(*) FROM (' + @sql + ') AS TEMP';
EXEC(@sqlrowcount);
IF @@ROWCOUNT > @limit BEGIN .... END
@sql
动态查询在哪里。然后我尴尬地意识到,EXEC(@sqlrowcount)
将永远返回1
,因为它返回一条记录,其值为记录数。
是否有一种(相对)优雅的方式来做到这一点,例如不将结果写入临时表?