Reputation: 3257
I have a query as below, which executes as per requirement.
DECLARE @count varchar(20)
SET @count = (SELECT COUNT(*) FROM emp)
PRINT 'Employee Count: '+@count
SELECT @count
But, if I want to do the same with the use if dynamic SQL i am not getting my desired result. My dynamic SQL code is as below:
DECLARE @count varchar(10)
DECLARE @sqlQuery varchar(500)
SET @sqlQuery = 'SET '+@count +'= (SELECT COUNT(*) FROM emp)'
EXEC (@sqlQuery)
PRINT 'Employee Count: '+@count
SELECT @count
This code gives me a NULL as output.
What should be done? Where have I gone wrong?
Upvotes: 1
Views: 218
Reputation: 121902
Try to add the output parameter for -
DECLARE
@SQL NVARCHAR(500)
, @OutputNum VARCHAR(10)
SET @SQL = N'SELECT @OUT = COUNT(1) FROM dbo.emp'
EXEC sys.sp_executesql
@SQL
, N'@OUT INT OUTPUT'
, @OUT = @OutputNum OUTPUT
PRINT 'Employee Count: '+ @OutputNum
SELECT @OutputNum
Output -
Employee Count: 103
Upvotes: 5