TSQL QUERY to dump table into a file? - sql

I want to dump a tale into a text file I am using following command -
bcp tablename out myTable.dat -T -C
But got error it says incorrect symbol near bcp.
I am not sure why I am getting this.

From #Code Monkey's Link : http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/
try this
declare #sql varchar(8000)
select #sql = 'bcp [dbname].[dbo].[tablename] out myTable.dat -c -t, -T -S'+ ##servernameexec
master..xp_cmdshell #sql
where dbname is the name of your database, and replace dbo with the name of the schema if not dbo

Related

BCP with WHERE clause Fails

When using BCP to export data from a table to an XML file this works perfectly:
declare #cmd nvarchar(255);
select #cmd = '
bcp "select AGENT,TERMCD ,MYAMOUNT,CAMPNAME,LCDATE,CAMPAIGNID from [MYDATABASE].[dbo].[CC1] row for xml auto, root(''rows''), elements" '
+ 'queryout "d:\temp\sample.xml" -S DESKTOP-2C2OAE9 -T -w -r -t';
exec xp_cmdshell #cmd;
go
However if I add a simple WHERE clause like below it fails.
declare #cmd nvarchar(255);
select #cmd = '
bcp "select AGENT,TERMCD ,MYAMOUNT,CAMPNAME,LCDATE,CAMPAIGNID from [MYDATABASE].[dbo].[CC1] WHERE AGENT=''Kelly Martens'' row for xml auto, root(''rows''), elements" '
+ 'queryout "d:\temp\sample.xml" -S DESKTOP-2C2OAE9 -T -w -r -t';
exec xp_cmdshell #cmd;
go
There are the errors:
NULL
Starting copy...
SQLState = 37000, NativeError = 102
Error = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'row'.
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to resolve column level collations
NULL
BCP copy out failed
NULL
I am actually going to have to use LCDATE which is varchar to compare to the current date but I wanted to do something simple initially since I am having problems but if you have thoughts on that too it would be welcome.
Your 'row' table alias moved to after the where, it should be after the table name
declare #cmd nvarchar(255);
select #cmd = '
bcp "select AGENT,TERMCD ,MYAMOUNT,CAMPNAME,LCDATE,CAMPAIGNID from [MYDATABASE].[dbo].[CC1] row WHERE AGENT=''Kelly Martens'' for xml auto, root(''rows''), elements" '
+ 'queryout "d:\temp\sample.xml" -S DESKTOP-2C2OAE9 -T -w -r -t';
exec xp_cmdshell #cmd;
go

Writing XML to the drive in SQL Server

I'm having a hard time working out how to write XML to my hard drive in SQL Server. I gather I could do something like this:
EXEC xp_cmdshell 'bcp "###INSERT SELECT/FOR XML QUERY###" queryout "C:\test.xml" -T -c -t'
But my SELECT/FOR XML query runs to about 40 lines so I'd rather not. I tried storing the XML as #storedXML, saving it in a table and then querying that table with bcp:
CREATE TABLE xmlOutput(outXML xml)
INSERT INTO xmlOutput(outXML)
VALUES (#storedXML)
DECLARE #sqlCmd VARCHAR(1000)
SET #sqlCmd = 'bcp "SELECT * FROM xmlOutput" queryout C:\test.xml -c -T -t'
EXEC xp_cmdshell #sqlCmd
But all that gets me is "Unable to open BCP host data-file".

Problems with bcp utility

I want to extract a SELCET query with the bcp utility. But it doesn't work. MS SQL underlines "bcp" marks it.
DECLARE #DBName NVARCHAR(MAX);
SET #DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + #DBName+']');
PRINT (' DATABASE SELECTED: '+ #DBName)
bcp "SELECT [Role ID],[Name] FROM [dbo].[Permission Set]" out "C:\Users\Public\Documents\test.txt" -c -T
The error message is:
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near 'bcp'.
Does anybody know the correct syntax? If I compare it with the examples on the docs.microsoft website (https://learn.microsoft.com/en-us/sql/tools/bcp-utility#o) I do not see my mistake.
You need to use xp_cmdshell procedure to execute the bcp command in T-SQL script
Declare #sql varchar(8000)
Select #sql = 'bcp "SELECT [Role ID],[Name] FROM [dbo].[Permission Set]" out "C:\Users\Public\Documents\test.txt" -c -T'
Exec master..xp_cmdshell #sql
bcp is a command line utility. It runs from a shell script (typically), not from T-SQL.
Within SQL code, you would normally use bulk insert. See the documentation here.

How to export SQL Server table data into text file as Insert command?

I have a table with bulk data (say 2 Million rows). I need to export this data into a text file.
I've approached Generate Scripts method by which it throws
System.OutOfMemoryExeception.
I need to some how convert the data into text file. Can sqlcmd approach be helpful? If so please suggest the steps.
Turn on xp_cmdshell in Facets and run this -
DECLARE #sql NVARCHAR(4000) = 'bcp "SELECT * FROM sys.schemas" queryout "D:\sample.txt" -S ' + ##servername + ' -T -w -r -t'
EXEC sys.xp_cmdshell #sql

Getting column names with BCP queryout

I need to BCP a table into a tab-delimited file, but I need the column names in the first record of the table. Question 1: Am I right that BCP does not have a switch for this? Question 2: If not, why?
I tried to do the following:
BCP "declare #colnames varchar(max); select #colnames=coalesce (#colnames+char(9), '')
+ Column_Name from db.information_Schema.columns where table_name='table1' order by
ordinal_position; select #colnames" queryout Table1_Columns.tsv -S?? -U?? -P?? -f** -e**
The format file looks like this:
9.0
1
1 SQLCHAR 0 100 "\r\n" 1 Column_Names SQL_Latin1_General_CP1_CI_AS
This gets me a file of the column names, then a second BCP command gets me a file of data, and I just DOS-copy the two together. Question 3: Am I clever or what? Question 4: Why doesn't it work? I get the error:
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Native Client]Host-file columns may be skipped only when
copying into the Server
bcp does not support exporting the column headers with the data, however there are some workarounds like exporting the headers in a separate file, then merging both the headers and data files as the following:
exec master..xp_cmdshell 'BCP "select 'SETTINGS_ID','GROUP_NAME'" queryout d:\header.csv -c -T -t,'
exec master..xp_cmdshell 'BCP "select SETTINGS_ID,GROUP_NAME from [DB]..[TABLE]" queryout "d:\columns.csv" -c -t, -T '
exec master..xp_cmdshell 'copy /b "d:\header.csv"+"d:\columns.csv" "d:/result.csv"'
You may also delete the unused files:
exec master..xp_cmdshell 'del "d:\header.csv"'
exec master..xp_cmdshell 'del "d:\columns.csv"'
Or maybe you can combine all the data in a view (adding headers) and export it