title: How to create text file in sql server
body: <p>I have a problem with sql server. I want to run a command in sql server for 691 times,(for each VID).</p>
  
  <p>But the values of VID column are not Sequential and Ascending. so how can I run this command.</p>
  
  <p>My means that I want to run this command for each VID, that the number of its value is 691, and the min value is 11, and the max value is 7668. And then I want to save results for  each VID in text file.</p>
  
  <p>The command is:</p>
  
  <pre><code>declare @vid integer
  
  DECLARE @FileName varchar(8000)
  
  declare @bcpCommand varchar(8000)
  
  set @vid = 1
  
  while (@vid &lt; 692)
  
  begin
  
  SET @FileName = 'd:\re'+ CONVERT(char(8),@vid)+'.txt'
  
  
  
  SET @bcpCommand =  'bcp "select ak_from,ak_to,w from [socialdb].[dbo].final where ???? "  queryout "'+ @FileName + '" -C -T -c -S SONY-VAIO\SQLEXPRESS1'
  
  EXEC master..xp_cmdshell @bcpCommand
  
  
  
  set @vid = (@vid + 1)
  
  end
  </code></pre>
  
  <p>I want to do this with sql server 2008. The first records is one of my table records.</p>
  
  <p>I should classification records according to vid, and each record that has a same vid must be in a seprat txt file.</p>
  
  <p>For saving in text file I use bcp. and I don’t have problem with that. My problem is with the Query in sql server that do this. As I said, the first records are  saved in table that its name is final.
  How to write the query for this?</p>