将标量查询结果返回到批处理文件变量中

时间:2011-07-22 16:52:38

标签: sql sql-server batch-file

我想执行标量数据库查询并将结果返回到批处理文件中的变量。

怎么会这样做?我看到的系统中最接近的I示例是基于标量查询结果返回退出代码。

    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

有人可以帮我解释语法吗?

这是一些sqlcmd帮助信息:

-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).

3 个答案:

答案 0 :(得分:4)

如何将它保存到没有标题的文件然后再读回内容?

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%

答案 1 :(得分:2)

我在批处理文件中使用它。它返回SQL Server数据库数据文件的LogicalFilename。这仅在数据库中有一个数据文件时才有效。

结果是环境变量DATABASEFILENAME被设置为说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

答案 2 :(得分:0)

你看过sqlcmd吗?