title: Use sp_executesql to run xp_cmdshell with variable
body: <p>Trying to run xp_cmdshell with sp_executesql without success, database is SQL Server 2008R2</p>
  
  <p>Here is the SQL</p>
  
  <pre><code>DECLARE @sql nvarchar(max) = N'EXEC xp_cmdshell ''BCP "SELECT data FROM TableA WHERE id = @id" queryout C:\Temp\test.dat -T -N'''
  EXEC sp_executesql @sql, N'@id numeric(19, 0)', @id = 1234
  </code></pre>
  
  <p>The error is</p>
  
  <pre><code>Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Must declare the scalar variable "@id".
  </code></pre>
  
  <p>Please help, thank you!</p>