1

I would like to know how I can export data from a select command to a normal text file from MSSQL using the xp_cmdshell bcp method.

I'm using SQL 2012 an my code looks like this :

Declare @filename varchar(50),
        @cmd varchar(4000),
        @file varchar(100)
set @filename = 'TestMe'
set @file = 'c:\' + @FileName + '.txt'
set @cmd = 'bcp "Select * from TableName" queryout"'
set @cmd = @cmd + @file + '" -T -is'
EXEC xp_cmdshell @cmd

The query executes successfully, but the it gives me an output that says:

bcp: Unable to open input file s: No such file or directory

I even tried creating the file and hardcoding the name, but to no avail. Any help would be greatly appreciated.

2 Answers 2

2

you are specifying the -i flag which is to specify an input file. Hence the command is interpreted as "use input file 's'" which of course doesn't exist...

you are specifying the -i flag which is to specify an input file. Hence the command is interpreted as "use input file 's'" which of course doesn't exist...

Just for reference, your BCP command should look like this:

bcp "Select * from TableName" queryout "OutputFilename" -d "DatabaseName" -T -n

where TableName is the name of the table, OutputFilename is the full path + file name and DatabaseName is the actual database. This assumes Trusted connection (-T), local server (didn't put in the -S switch), and automatically picks a format for the output columns (-n)

Hope that helps.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. It does help. The problem now is that it says : Error = [Microsoft][SQL Server Native Client 10.0]Unable to open BCP host data-file. I have given the folder full access.
Are you sure that the path exists from the server's point of view?
Hmm. Can you edit your question to include the bcp command that's being generated (also, did you try executing this on the command line) so we can have a look?
I've managed to find the problem by running it on the server in command prompt. It was a space issue on the drive. I couldn't believe it. Thank you very very much for your help.
:) always the last thing you check! glad its working.
2

Check if your SQL have permissions to access C:. This can be done easily by trying to backup something from SSMS on C:\

1 Comment

Rights is fine. Checked that first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.