Search code examples
sql-serversql-server-2008-r2bcp

SQL Server 2008 R2: Export data using bcp command and store bcp output into variable


I want to export data using bcp command and the output of the bcp command should be stored in the variable.

My try:

DECLARE @Result varchar(max)
DECLARE @SQL nvarchar(max)

SET @SQL = N'Execute xp_cmdshell ''bcp "SELECT * FROM EMP" QueryOut  "E:\BCP\Result.pec"   -T -t@_@ -c -o "E:\BCP\LogReport.txt"'''

EXEC sp_executesql @SQL, N'@Result nvarchar(75) OUTPUT', @Result =@Result output

PRINT(@Result)

But getting an error in the output:

output
------------------------------------------------------------------------------
bcp: Unable to open output file E:\BCP\LogReport.txt: No such file or directory
NULL

Questions:
1. How to store the above output result into the variable?
2. Given permission to the file and folder too, but still getting this error.


Solution

  • ---------------------------------------- 1 -------------------------------------------
    
    DECLARE @Result TABLE
    (error_msg VARCHAR(800))
    
    DECLARE 
        @SQL varchar(8000),
        @Result_var VARCHAR(MAX)=''
    
    SET @SQL = N'bcp "SELECT * FROM <MY_DATABASE>.<MY_SCHEMA>.<MY_TABLE>" QueryOut  "E:\BCP\Result.pec"   -T -t@_@ -c -o "E:\BCP\LogReport.txt"'''
    
    -- Insert the output from xp_cmdshell into the table @Result
    INSERT INTO @Result (error_msg)
    EXEC xp_cmdshell @SQL
    
    -- Merge the rows
    SELECT @Result_var = @Result_var + ' ' + ISNULL(error_msg,'') FROM @Result
    
    -- Output in variable
    PRINT @Result_var
    --------------------------------------------------------------------------------------
    

    2. For me, your command works, check access to folders and subfolders (for database user), check permissions on the sql server.