Search code examples
sqlsql-servercmdsqlcmd

Is it possible to keep the headers but remove the hyphens of a sql output using sqlcmd


Objective:

I was able to remove the hyphens when executing a sql query through sqlcmd using

|findstr /v /c:"---"

The issue however, is I can't combine the above code with my "-o" variable as such:

sqlcmd -S INSTANCENAME -s ";" -Q "SET NOCOUNT ON; SELECT top 5 * FROM table" |findstr /v /c:"---" -o output.csv

Error message:

FINDSTR: Cannot open output.csv

Note: I need to keep my headers.


Solution

  • Well, the findstr command does not feature an option -o to create an output file. However, you can use output redirection to write the result into a file, like this:

    sqlcmd -S INSTANCENAME -s ";" -Q "SET NOCOUNT ON; SELECT top 5 * FROM table" | findstr /V /C:"---" > "output.csv"
    

    Regard that this will overwrite the file output.csv if it already exists without notice. To append to the output file rather than to overwrite it, just replace > by >>.