title: How can I BCP queryout with filename from table?
body: <p>I'm extracting many BLOBs to files using BCP and wonder if there's a way to give each file a unique name using an ID field from the SQL table.
  This works:</p>
  
  <pre><code>DECLARE  @Command NVARCHAR(4000)  
  SET @Command = 'bcp "SELECT FileData FROM MyDB.dbo.Attachments 
                  WHERE Hist_ID = ''00004F13''" 
                  queryout "C:\Wha.pdf" -T -c -C RAW -S SERVERNAME -U SA -P pa$$word'  
  EXEC xp_cmdshell   @Command
  </code></pre>
  
  <p>But to get the filename, I've tried:</p>
  
  <pre><code>DECLARE @FileName varchar(50),  
  @Command NVARCHAR(4000)  
  SET @FileName = Hist_ID+'wha.PDF'  
  SET @Command = 'bcp "SELECT FileData FROM MyDB.dbo.Attachments 
                  WHERE Hist_ID = ''00004F13''"     queryout'  
  SET @Command = @Command + 'C:\' + @FileName + '-T -c -C RAW 
                             -S SERVERNAME -U SA -P pa$$word'  
  EXEC xp_cmdshell   @Command
  </code></pre>
  
  <p>I get an error:  Invalid column name 'Hist_ID'.
  Is there some way to do this? Thanks for any help!</p>