2011-07-22 66 views
4

我想執行標量數據庫查詢並將結果返回到批處理文件中的變量。將標量查詢結果返回到批處理文件變量

如何做到這一點?我看到的系統中最接近的例子是,如果我根據標量查詢結果返回退出代碼。

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

回答

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 
+0

你的答案看起來不錯。只是一個後續問題:我會撒謊以完全限定到sqlcmd的路徑,例如,SET sqlcmd =「C:\ Program Files \ Microsoft SQL Server \ 100 \ Tools \ Binn \ sqlcmd.exe」,但是當我這樣做時,我得到「文件名,目錄名稱或卷標語法不正確。」 – ChadD

+0

下面是修改後的行: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

+0

http://stackoverflow.com/questions/6860897/issue-executing-an-exe-when-the-path-has-spaces – ChadD

0

你看着sqlcmd

+0

是的,但我需要幫助的語法。 – ChadD

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%