views:

61

answers:

2

Hi all

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

+1  A: 

try this:

SET NOCOUNT ON;
SELECT
    [Name]
    FROM (SELECT TOP(10)
              2 AS SortBy, [name]
              FROM sysobjects 
          UNION
          SELECT 1, 'Name'
         ) dt
    ORDER BY [Name]

OUTPUT FROM SSMS:

Name
----------------------------------------------
Name
sysallocunits
sysfiles1
sysftinds
syshobtcolumns
syshobts
sysowners
sysprivs
sysrowsetcolumns
sysrowsets
sysserefs

leave the "-h -1" parameter and the column headings will be removed, but the "Name" row will still appear in the result set first.

KM
Hey KM. Thanks thats quite an innovative solution. I would prefer not to alter the queries though.
Karl
A: 

I far as I can see, you cannot get rid of "---" line when using sqlcmd.

juur