How to Create a CSV with SQLCMD for Import into Another Database

csvsql serversqlcmdUbuntu

I may be doing this all the wrong way so please point me in the right direction if I am missing something.

I have an Ubuntu server with SQLCMD installed and a Windows Server with a MSSQL database.

I have a working script to output data from a query out of the MSSQL database into a CSV file already BUT its not quite right. SQLCMD creates 2 excess features which I would like to remove and there is no real definitive guide on how to do it.

Sample output:

header1,header2
-----,-----
data1,data2
data3,data4

Network packet size (bytes): 4096
1 xact[s]:
Clock Time (ms.): total       445  avg   445.0 (2.2 xacts per sec.)

So the features here I do not want in a CSV are quite obvious. The — lines and the output data at the bottom.

My script looks something like this so far:

sqlcmd -S databaseserver -U "sa" -d database -p -W -Q "set nocount on; SELECT x as data, count(*) as datacount FROM location WHERE x IS NOT NULL GROUP BY x" -s "," -o output.csv -r0

I am happy to make .sh files with actions which take place after so any native ubuntu scripting method which can "finish the job" is acceptable. I am not that confident at writing the scripts but can usually work out what they do.

Best Answer

So the features here I do not want in a CSV are quite obvious. The --- lines and the output data at the bottom.

To remove the output at the bottom, omit the -p parameter.

sqlcmd -S databaseserver -U "sa" -d database -p -W -Q "set nocount on; SELECT x as data, count(*) as datacount FROM location WHERE x IS NOT NULL GROUP BY x" -s "," -o output.csv -r0

Result:

enter image description here

According to the documentation on sqlcmd

You can use the -h parameter to control the headers

Use -1 to specify that headers not be printed. Any value that is not valid causes sqlcmd to generate an error message and then exit.

But you can only remove or change the frequency of the headers.

sqlcmd -S databaseserver -h -1 -U "sa" -d database -W -Q "set nocount on; SELECT x as data, count(*) as datacount FROM location WHERE x IS NOT NULL GROUP BY x" -s "," -o output.csv -r0

Result:

enter image description here

The not so clean solution that was also used here could be to print or select the column headers before running the select.

sqlcmd -S databaseserver -h -1 -U "sa" -d database -W -Q "set nocount on; PRINT('header1,header2'); SELECT x as data, count(*) as datacount FROM location WHERE x IS NOT NULL GROUP BY x" -s "," -o output.csv -r0

Result:

enter image description here