title: SQL getting value of dynamic query into a variable
body: <p>I am selecting the <code>COUNT</code> 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 <code>NULL</code> (I have tested the query and it returns a value). Any tips? </p>
  
  <pre><code>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
  </code></pre>