1

I am selecting the COUNT of something in a SQL Server 2016 database using a dynamic SQL query and want that value placed into a variable. Below is the SQL statement which I was sure was correct, but the value I'm getting is NULL (I have tested the query and it returns a value). Any tips?

DECLARE @Output INT 

SELECT @SqlCommand = 'SELECT COUNT(ServerName) FROM ' + @TableReference + ' WITH (NOLOCK) WHERE ServerName = ''' + @PackageEndPoint + '''' 

EXEC sp_executesql @SqlCommand, N'@Output INT OUTPUT', @Output = @Output OUTPUT

SELECT @StagingRecordCount = @Output

1 Answer 1

2

You need to assign your @Output variable to your result count.

@Output = COUNT(ServerName)

complete script

DECLARE @Output INT 

SELECT @SqlCommand = 'SELECT @Output = COUNT(ServerName) FROM ' + @TableReference + ' WITH (NOLOCK) WHERE ServerName = ''' + @PackageEndPoint + ''''

EXEC sp_executesql @SqlCommand, N'@Output INT OUTPUT',@Output = @Output OUTPUT
SELECT  @StagingRecordCount = @Output
SELECT @StagingRecordCount
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.