28

Using the following sqlcmd script:

sqlcmd -S . -d MyDb -E -s, -W -Q "select account,rptmonth, thename from theTable"  
> c:\dataExport.csv

I get an csv output file containing

acctnum,rptmonth,facilname

-------,--------,---------
ALLE04,201406,Allendale Community for Senior Living-LTC APPL02,201406,Applewood Estates ARBO02,201406,Arbors Care Center
ARIS01,201406,AristaCare at Cherry Hill
. . .

(139 rows affected)

Is there a way to get rid of the dashed line under the column headers : -------,--------, but keep the column headers?

and also a way to get rid of the two lines used for the row count on the bottom?

I tries using parm -h-1 but that got rid of the column headers as well as the dashed line.

Lill Lansey
  • 4,775
  • 13
  • 55
  • 77

11 Answers11

63

Solutions:

1) To remove the row count ("(139 rows affected)") you should use SET NOCOUNT ON statement. See ref.

2) To remove column headers you should use -h parameter with value -1. See ref (section Formatting Options).

Examples:

C:\Users\sqlservr.exe>sqlcmd -S(local)\SQL2012 -d Test -E -h -1 -s, -W -Q "set nocount on; select * from dbo.Account" > d:\export.txt. 

or

C:\Users\sqlservr.exe>sqlcmd -S(local)\SQL2012 -d Test -E -h -1 -s, -W -Q "set nocount on; select * from dbo.Account" -o "d:\export2.txt"
Bogdan Sahlean
  • 19,233
  • 3
  • 42
  • 57
  • 2
    Thanks for the "nocount" help. That worked. However, as I stated in my question, I need the column heading titles, but not the dashed line, and -h -1 also removes the column heading titles. Is there a way to get rid of the dashed line under the column headers : -------,--------, but keep the column headers? – Lill Lansey Jul 07 '14 at 12:43
  • 1
    I am awarding you the bounty although you answered only part of the question. Thank you for that. – Lill Lansey Jul 10 '14 at 13:41
  • 1
    @LillLansey you are probably going to need to select the column names using meta data (if dynamically) or manually select the column names in quotes and then union all the data underneath the columns. That can be your -Q query. Combining that method with this method should produce what you want. Or you could also create a process to open the file and add the headers and then close the file. But that's going to be a few more lines of code. – DtechNet Dec 17 '18 at 18:35
  • If you want to remove the dashed line but still keep the headers, you want to use JSkyS' answer below. – Weihui Guo Apr 16 '19 at 19:53
23

The guy with the top answer didn't answer how to remove the dashed line. This is my awesome solution.

  1. First include -h -1 which removes both the dashed line and header
  2. Then before your select statement manually inject the header string that you need with a PRINT statement. So in your case PRINT 'acctnum,rptmonth,facilname' select..*...from...

Sorry I'm 4 years and 9 months late.

JSkyS
  • 413
  • 6
  • 14
9

Use the following;

sqlcmd -S . -d MyDb -E -s, -h-1 -W -Q "set nocount on;select 'account','rptmonth', 'thename';select account,rptmonth, thename from theTable"  
> c:\dataExport.csv
  • remove the header -h-1
  • remove row count [set nocount on;]
  • add header select [select 'account','rptmonth', 'thename';]
  • add your select [select account,rptmonth, thename from theTable;]
Waleed A.K.
  • 1,596
  • 13
  • 13
2

To remove the Row Count: Add the below to your SQL statement

    SET NOCOUNT ON;

To remove the hyphen row try the following upon successful execution:

    findstr /v /c:"---" c:\dataExport.csv > c:\finalExport.csv

I use "---" as all my columns are over 3 characters and I never have that string in my data but you could also use "-,-" to reduce the risk further or any delimiter based on your data in place of the ",".

Dan
  • 41
  • 2
2

In my case worked well as :

type Temp.txt | findstr /v -- > DestFile.txt

2

This is the one line solution, without doing anything inside the stored procedure to append the column headers:

sqlcmd -S . -d MyDb -E -s, -W -Q "select account,rptmonth, thename from theTable"
| findstr /v /c:"-" /b > "c:\dataExport.csv" & exit 0

What this does is it intercepts all console output and replaces the "-" char BEFORE it redirects to the output file. There is NO need to output to intermediary file. And you will need a one-liner command if you use an agent to run these commands remotely on the sql server machines, which most of the times are locked from hosting *.bat files (which you'd need for multiline commands). I added the "exit 0" at the end to not fail the caller application overall. You may remove it starting "& exit 0" if you don't care about that.

This one liner is why I chose sqlcmd over bcp out, by the way. BCP, although optimized for speed, cannot output column headers unless doing the ugly trick within the stored proc, to append them there as a union all.

Just in case you have access to writing a bat file that contains this one liner, you MUST add @ECHO OFF before it. Otherwise the console output will also have the actual command.

Hope it helps.

nenea
  • 127
  • 8
  • what if your data returned by select contains hyphen? – Nikita Jun 20 '22 at 14:34
  • Works fine even with hyphen in the data returned. Did you try it? – nenea Dec 06 '22 at 14:49
  • sqlcmd -S myserver -d mydb -E -s, -W -Q "SELECT * FROM [COMMON].[COVERAGE_CD] WHERE COVERAGE_DESC LIKE '%-%'" | findstr /v /c:"-" /b > "c:\dataExport.csv" & exit 0 – nenea Dec 06 '22 at 14:50
  • COVERAGE_CD,INSERT_ID,INSERT_TMSTMP,UPDATE_ID,UPDATE_TMSTMP,DELETE_IND,COVERAGE_DESC,THRD_PARTY_IND LBI,stg,2012-05-15 23:14:20.233,stg,2012-05-15 23:14:20.233,N,Liability - Bodily Injury,Y LPD,stg,2012-05-15 23:14:20.233,stg,2012-05-15 23:14:20.233,N,Liability - Property Damage,Y NO_LPD,stg,2012-05-15 23:14:20.233,stg,2012-05-15 23:14:20.233,N,Not Liability - Property Damage,N – nenea Dec 06 '22 at 14:51
  • So yes, it does work – nenea Dec 06 '22 at 14:51
  • you have said "`What this does is it intercepts all console output and **replaces the "-" char** BEFORE it redirects to the output file`". So if output contains "-" all of them should be replaced, even if we need to save the "-" in the actual data rows. btw, the script in comment a little bit different from the answer, the pattern is "%-%" instead of "-". – Nikita Dec 08 '22 at 08:41
  • so I thought, that "-" in data will be also removed, not only the "-" for the header – Nikita Dec 08 '22 at 08:42
  • If you look at the output I posted above, the dates ("2012-05-15") and some text fields ("Liability - Bodily Injury") kept the dash. So it works. – nenea Mar 15 '23 at 19:46
  • I have already forgotten details) but remember that your answer was helpful, thank you for posting – Nikita Mar 20 '23 at 16:18
1

In addition, if you want to query out all records in a table, you can code as

  1. SET NOCOUNT ON;
  2. SELECT SUBSTRING((SELECT ','+ COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=N'%table_name%' FOR XML PATH('') ), 2, 9999);
  3. SELECT * FROM %table_name%

Assign the above queries into a variable %query%. The the command will be looks like as below.

SQLCMD -h -1 -W -E -S %sql_server% -d %sql_dabase% -Q %query% -s"," -o output_file.csv
Z.T. Wai
  • 11
  • 2
  • 2
    How is that an improvement to the answer that was accepted 5(!) years ago? You add a select that goes unexplained. As well as parameters that the OP did not use. You should explain these. – Markus Deibel Sep 17 '19 at 05:15
1

With SQL Server 2017 (14.x) and later you can print header with:

SELECT string_agg(COLUMN_NAME, ', ') within group (order by ORDINAL_POSITION asc) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='YOUR_TABLE_NAME'
Drashti Kheni
  • 1,065
  • 9
  • 23
0

1.Create the file first with the header columns

2.Apprend the sqlcmd output to the file using the option -h-1

echo acctnum,rptmonth,facilname > c:\dataExport.csv sqlcmd -S . -d MyDb -E -s, -h-1 -W -Q "select account,rptmonth, thename from theTable" >> c:\dataExport.csv

0

I used another solution to solve the issue of removing the dashed line below the header.

DECLARE @combinedString VARCHAR(MAX);

SELECT @combinedString = COALESCE(@combinedString + '|', '') + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME  = 'YOUR_TABLE_NAME'

Then just use Print @combinedString above your select statement. I used pipe delimiter.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
0

Kind of late to the party but if you're on Linux you can use sed to remove the second line after the file is produced like this:

sed -i '2d' exported.csv
Spyros El.
  • 423
  • 3
  • 13