title: Send Query result into a Text file in SqlServer
body: <p>I want to send the result from a scalar variable into a text file,</p>
  
  <p>My Code looks like this </p>
  
  <pre><code> DECLARE @test varchar(10)
  
   SET @test='This is sample text'
  
   EXEC master..xp_cmdshell'bcp ' + @test + ' queryout "D:\sample.txt" -S LocalHost -U 
   sa -P 123 -c  -T -t' 
  </code></pre>
  
  <p>But this is showing the following errors</p>
  
  <pre><code> output
   usage: bcp {dbtable | query} {in | out | queryout | format} datafile
   [-m maxerrors]            [-f formatfile]          [-e errfile]
   [-F firstrow]             [-L lastrow]             [-b batchsize]
   [-n native type]          [-c character type]      [-w wide character type]
   [-N keep non-text native] [-V file format version] [-q quoted identifier]
   [-C code page specifier]  [-t field terminator]    [-r row terminator]
   [-i inputfile]            [-o outfile]             [-a packetsize]
   [-S server name]          [-U username]            [-P password]
   [-T trusted connection]   [-v version]             [-R regional enable]
   [-k keep null values]     [-E keep identity values]
   [-h "load hints"]         [-x generate xml format file]
   NULL
  </code></pre>
  
  <p>Dont know how to give the format assigning a scalar variable value in bcp command
     Please any one help.</p>
  
  <p>And tried in this way also </p>
  
  <pre><code>  Create table #sample
    (
     productid int
    )
  
    Insert into #sample(productid) values(1001098)
  
    EXEC master..xp_cmdshell'bcp "select * from #sample" queryout "D:\sample.txt" -S 
    LocalHost -U sa -P 123 -c  -T -t' 
  </code></pre>
  
  <p>It gives as Error that</p>
  
  <pre><code>   #sample does not exist (in bcp command line) 
  </code></pre>
  
  <p>Can any one please solve this.
       Thanks in advance.</p>