title: Assign output of dynamic SQL to a variable (without stored proc)
body: <p>I have the code below, where I want to get the id of a row via dynamic SQL.</p>
  
  <p>Please note that variables <code>@posselect</code> and <code>@catselect</code> are filled, but I left that out for overview.</p>
  
  <pre><code>declare @SQL nvarchar(1000)
  declare @posselect nvarchar(50)
  declare @catselect nvarchar(100)
  
  declare @bannerid int
  
  SET @SQL = 'SELECT TOP 1 @id = id FROM banners
              WHERE publishdate &lt; GETDATE() 
              AND depublishdate &gt; GETDATE()' + @posselect + @catselect + 
             'ORDER BY [views] ASC'
  
  EXEC sp_executesql @SQL, @bannerid = @id output  'on this line I get the error
  
  print '@bannerid:'+STR(@bannerid)
  </code></pre>
  
  <p>I get the error: </p>
  
  <blockquote>
    <p>Must declare the scalar variable "@id".</p>
  </blockquote>