1

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?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.