Search code examples
sql-serverbatch-filesqlcmd

Loop over SQLCMD results on batch file


I'm using the folling .cmd to get the values returned by one sql sentence.

@echo off
SET SERVER=.\SQLExpress 
SET SQLCMD="C:\Program Files\Microsoft SQL Server\110\Tools\Binn\sqlcmd.exe"
for %%f in (%SQLCMD%) do set alternatepath=%%~sf

SET EXEC_LINE=%alternatepath% -S %SERVER% -d SkpMaster -h-1 -Q "set nocount on; select distinct id from sometable "

for /F "usebackq delims=" %%i in (`%EXEC_LINE%`) do (
    set count=%%i
    echo %count%
)

if not defined count (
    echo Failed to execute SQL statement 1>&2
)

The SQL return 4 occurrences, but the echo print 4 times the 1º ocurrence.

Maybe I'm not using correctly the "delims=" option, I have also tested with "tokens=*" with the same result. Any idea?


Solution

  • Fixed after handle the parameter %%i in a different way.

    @echo off
    SET SERVER=.\SQLExpress 
    SET SQLCMD="C:\Program Files\Microsoft SQL Server\110\Tools\Binn\sqlcmd.exe"
    for %%f in (%SQLCMD%) do set alternatepath=%%~sf
    
    SET EXEC_LINE=%alternatepath% -S %SERVER% -d SkpMaster -h-1 -Q "set nocount on; select distinct id from sometable "
    
    for /F "usebackq delims=" %%i in (`%EXEC_LINE%`) do call :processline %%i
    
    if not defined count (
        echo Failed to execute SQL statement 1>&2
    )
    
    pause
    goto :eof
    
    :processline
    echo line=%*
    goto :eof
    
    :eof