I have a pretty simple question (and these are typically the ones I spend most of my time tearing my hair out about). I am using a batch file to execute all the .sql queries that are in the same directory as the batch, and to save all their results to various .csv file.
Here is my code:
@echo off
REM Check that all parameters are present
@IF "%1"=="" goto error
@IF "%2"=="" goto error
@IF "%3"=="" goto error
@IF "%4"=="" goto error
REM For every *.sql file in this folder "." and all its subfolders (/R), do the following:
@for /R "." %%F in (*.sql) do (
REM Print the command to be executed:
@echo Database : @SqlCmd -S %1 -U %2 -P %3 -d %4 -I -l60 -i "%%F" -o "%%F.output.csv" -h-1 -s"," -w 1000 -W
REM Execute the command:
@SqlCmd -S %1 -U %2 -P %3 -d %4 -I -l60 -i "%%F" -o "%%F.output.csv" -h-1 -s"," -w 1000 -W
)
goto :EOF
:error
@echo Incorrect syntax :
@echo extract.cmd [servername] [user id] [password] [databasename]
@echo
@pause
goto :EOF
As a test, I run the following query:
select top(10) [name] from sysobjects
which outputs:
sysrscols
sysrowsets
sysallocunits
sysfiles1
syspriorities
sysfgfrag
sysphfg
sysprufiles
sysftinds
sysowners
(10 rows affected)
This works fine, except for two things. Firstly, I need to have the column headers output as well. So I remove the "-h -1" parameter, which then gives:
name
----
sysrscols
sysrowsets
sysallocunits
sysfiles1
syspriorities
sysfgfrag
sysphfg
sysprufiles
sysftinds
sysowners
(10 rows affected)
which is great except for the fact that I don't want the horizontal rule "------" between the heading and the first row of data.
Also, I don't want the "(10 rows affected)" line to be output.
Does someone know how I could achieve this?
Thanks
Karl
I far as I can see, you cannot get rid of "---" line when using sqlcmd.
You can use BCP instead of SQLCMD. Here's a batch file to run your query on multiple SQL servers. Copy this code in CSV.CMD in C:\SCRIPT, then create a SERVERS.LST in the same folder with with one servername per line. then try running:
CSV.CMD "select * from master..sysdatabases"
This will work only with Windows authentication but you can change the code to your need.
try this:
OUTPUT FROM SSMS:
leave the "-h -1" parameter and the column headings will be removed, but the "Name" row will still appear in the result set first.