Question

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? Can any help me saying where have I gone wrong?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top