我想執行標量數據庫查詢並將結果返回到批處理文件中的變量。將標量查詢結果返回到批處理文件變量
如何做到這一點?我看到的系統中最接近的例子是,如果我根據標量查詢結果返回退出代碼。
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).
你的答案看起來不錯。只是一個後續問題:我會撒謊以完全限定到sqlcmd的路徑,例如,SET sqlcmd =「C:\ Program Files \ Microsoft SQL Server \ 100 \ Tools \ Binn \ sqlcmd.exe」,但是當我這樣做時,我得到「文件名,目錄名稱或卷標語法不正確。」 – ChadD
下面是修改後的行:FOR/F「usebackq tokens = 1」%% i IN('%sqlcmd%-S%server%-d%db%-w200 -h-1 -E -Q「set nocount on; select REPORTING_DATE FROM dbo.CURRENT_REPORTING_DATE「')DO set REPORTING_DATE = %% i – ChadD
http://stackoverflow.com/questions/6860897/issue-executing-an-exe-when-the-path-has-spaces – ChadD