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

后端 未结 8 1757
难免孤独
难免孤独 2021-02-01 06:09

Using the following sqlcmd script:

sqlcmd -S . -d MyDb -E -s, -W -Q \"select account,rptmonth, thename from theTable\"  
> c:\\dataExport.csv
<
相关标签:
8条回答
  • 2021-02-01 06:36

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

    0 讨论(0)
  • 2021-02-01 06:39

    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;]
    0 讨论(0)
  • 2021-02-01 06:40

    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.

    0 讨论(0)
  • 2021-02-01 06:46

    In my case worked well as :

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

    0 讨论(0)
  • 2021-02-01 06:46

    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.

    0 讨论(0)
  • 2021-02-01 06:49

    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 讨论(0)
提交回复
热议问题