title: Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to open BCP host data-file
body: <p>I have 1 table which contains a KEY and a file ref at the end of each record. I also have another table which has a lot of records with a KEY contained against each record. I then link both tables together by the KEY and wish to export the data based on the file ref. When I run it as a select query it works fine... but when I run it with the purpose of generating a file for each file ref it fails with the error in the title preceded by the line <code>'SQLState = S1000, NativeError = 0'</code>. I have access to the directory and I'm running the code on the server. Any guidance would be appreciated.</p>
  
  <pre><code>    DECLARE @File_number INT
      DECLARE @SQL VARCHAR(8000)
      DECLARE file_num CURSOR READ_ONLY FAST_FORWARD LOCAL FOR 
          SELECT DISTINCT File_number FROM map_sequence_tranid ORDER BY 1
      OPEN file_num
      FETCH NEXT FROM file_num INTO @File_number
      WHILE @@FETCH_STATUS = 0 BEGIN
      SELECT @SQL = 'bcp "SELECT b.File_number, a.[Field1], b.[Field2] from Table1 a, Table2 b where a.[Key]=b.[key] and b.File_number=' + CAST(@File_number as varchar(10)) + ' order by a.[key]" queryout ''E:\Path\file' + CAST(@File_number AS VARCHAR(10)) + '.txt'' -c -T -t'','' -S ' + @@SERVERNAME
      EXEC master..xp_cmdshell @SQL
      FETCH NEXT FROM file_num INTO @File_number
  END
  CLOSE file_num
  DEALLOCATE file_num
  </code></pre>