Cha*_*adD 5 sql sql-server batch-file
我想执行标量数据库查询并将结果返回到批处理文件中的变量中。
一个人会怎样做呢?我在我们的系统中看到的最接近的示例是,如果我根据标量查询结果返回退出代码。
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
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决语法问题吗?
这是一些 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).
Run Code Online (Sandbox Code Playgroud)
我在批处理文件中使用它。它返回 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
Run Code Online (Sandbox Code Playgroud)