Extract value returned from dynamic SQL

ぐ巨炮叔叔 提交于 2019-12-04 05:20:55

One way;

--base sql
declare @sql  nvarchar(255) = N'select * from master.dbo.spt_values'

--count wrapper
declare @sqlb nvarchar(255) = N'set @count=(select count(*) from (' + @sql + ') T)'

declare @count int
exec sp_executesql @sqlb, N'@count int output', @count output

select 'rows=',@count

You could also use TOP to enforce a limit, running the same statement twice is not very efficient.

The problem you are running into is that exec statements preserve the previous @@rowcount value, which in your case is 1 from the set statement (all set statements make @@rowcount become 1). This is necessary because execute creates its own batch.

The best way to get the value is to use sp_executesql with an output paramater. That would look something like:

declare @numRows int
declare @sql nvarchar(max)
set @sql = N'Select @numRows= count(*) from dbo.temp'

exec sp_executesql @sql, N'@numRows int output', @numRows output

--Put your if statement here using @numRows

This uses sp_executesql's ability to have output parameters to return the value from the count.

One good source for more details on dynamic queries in general that I recommend to all serious SQL programms is The Curse and Blessing of Dynamic SQL which explains how to paramaterize sp_executesql and why you might want to along with several other related topics.

Declare @Rowcount int
SELECT @RowCount = count(1) 
FROM         
dbo.tblUserAuditLog 
    LEFT OUTER JOIN dbo.tblUsers 
    ON dbo.tblUserAuditLog.intUserIdFK = dbo.tblUsers.intUserId


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]
    , @RowCount
FROM         
dbo.tblUserAuditLog 
    LEFT OUTER JOIN dbo.tblUsers 
    ON dbo.tblUserAuditLog.intUserIdFK = dbo.tblUsers.intUserId
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!