Sqlcmd to generate file without dashed line under header, without row count

孤街浪徒 提交于 2019-12-02 20:57:50

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"

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.

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;]

In my case worked well as :

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

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 ",".

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!