Return a scalar query result into a batch file variable

10,549

Solution 1

I use this in a batch file. It returns the LogicalFilename for a SQL Server Database data file. This only works if there is one data file in the DB.

So the result is the environment variable DATABASEFILENAME is set to say AdventureWorks_Data.

FOR /F "usebackq tokens=1" %%i IN (`sqlcmd -w200 -h-1 -E -Q"set nocount on; Select df.name  From sysdatabases as d Inner Join sysaltfiles as df on d.dbid=df.dbid Where d.name ='$(DatabaseName)' and df.Fileid =1"`) DO set DATABASEFILENAME=%%i

Solution 2

How about saving it to a file without headers then reading the contents back in?

sqlcmd -S(local)\SQLExpress -dMyDatabase -Umyuser -Pmypassword -W -h -1 -Q  "SELECT Top 1 MyValue FROM MyTable" -o sqlcmdoutput.txt 
set /p x= <sqlcmdoutput.txt
del sqlcmdoutput.txt
echo My scalar value is %x%
Share:
10,549
Chad
Author by

Chad

Updated on June 07, 2022

Comments

  • Chad
    Chad almost 2 years

    I would like to perform a scalar database query and return the result into a variable in a batch file.

    How would one do this? The closest I example in our system that I see is if I return an exit code based on a scalar query result.

        Z:\SQL2005\90\Tools\Binn\sqlcmd -S servername -dCLASS -E -Q "EXIT(select case run_type when 'Q' then 200 else 100 end from cycle_date where cycle = '1')">NUL
        if %errorlevel% == 200 call %SQLSERVER%
    QRTLY.BAT               
        if %errorlevel% == 100 call %SQLSERVER%
    MTHLY.BAT
    

    Can someone help me with the syntax?

    Here's some sqlcmd help info:

    -v var = value[ var=value...] 
    Creates a sqlcmdscripting variable that can be used in a sqlcmd script. Enclose the value in quotation marks if the value contains spaces. You can specify multiple var="values" values. If there are errors in any of the values specified, sqlcmd generates an error message and then exits.
    
    sqlcmd -v MyVar1=something MyVar2="some thing" 
    
    sqlcmd -v MyVar1=something -v MyVar2="some thing" 
    
    -x disable variable substitution 
    Causes sqlcmd to ignore scripting variables. This is useful when a script contains many INSERT statements that may contain strings that have the same format as regular variables, such as $(variable_name).