首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >sql脚本变量默认值

sql脚本变量默认值
EN

Stack Overflow用户
提问于 2010-09-20 02:50:44
回答 5查看 9.2K关注 0票数 13

我有一个脚本文件,例如test.sql。我想在sqlcmd模式下使用:r test.sql从另一个脚本调用它,比方说caller.sql。这很好用,但我想在test.sql中使用脚本变量。当我从caller.sql调用test.sql时,我可以设置脚本变量,一切都很正常。但是,我希望使用脚本值的默认值,以便如果调用者没有设置变量,或者如果我直接(不是从caller.sql)运行test.sql,则脚本变量将默认为设置值。

我尝试过像这样的东西

代码语言:javascript
运行
复制
begin try
 select '$(grip)'
 select 'grip value was found'
end try
begin catch
 select 'grip value was missing'
end catch

但我只得到了以下消息:发生了致命的脚本错误。未定义变量夹点。

我需要在test.sql中做些什么,这样它才能处理被调用者传递或不被传递的“grip”?我使用的是MS SQL 2005

EN

回答 5

Stack Overflow用户

发布于 2011-12-13 14:38:07

有一个有限的解决方法(我只在SS2008R2上测试过它):

简单版本-如果您愿意不使用:on error exit / sqlcmd.exe -b

代码语言:javascript
运行
复制
:on error ignore -- Ensures that sqlcmd.exe will not fail when referencing an undefined scripting variable. Remove this if you want your script to work in SSMS in regular mode, too.
Declare @valueOrDefault as nvarchar(max)= N'$(value)';    
if @valueOrDefault = N'$' + N'(value)' set @valueOrDefault = N'default value'; -- Test if there is a value and, if not, assign a default; note the splitting of the reference string to avoid expansion.

-- use @valueOrDefault from now on

注意:

  • 由于T-SQL变量不能跨批处理工作,因此您不能启动另一个批处理(使用GO),因此不能切换到使用:on error exit进行健壮的错误处理。因此,您必须在脚本的其余部分进行自己的错误处理-这不是微不足道的;请参阅SQL Server - stop or break execution of a SQL script
  • If删除:on error ignore为了使脚本在常规模式下在SSMS中工作,请确保在使用sqlcmd.exe调用该脚本时未指定-b选项,因为如果引用的脚本变量不存在,则会阻止整个脚本运行。
  • 通过将脚本变量有效地转换为常规T-SQL变量,您不能在T-SQL需要文字的位置使用该值,例如CREATE database语句中的数据库名称。
  • 如果未定义脚本变量,则会将以下警告输出到stderr:'variableName‘脚本变量未定义。

健壮的版本-更麻烦,但支持:on error exit,这是明智的:

代码语言:javascript
运行
复制
-- Store the default value in the context info (session-level storage accessible across batches that holds up to 128 bytes).
declare @binDefaultValue varbinary(128)= CAST(N'default value' AS varbinary(128));
set CONTEXT_INFO @binDefaultValue;
go -- Make the set CONTEXT_INFO statement take effect.

-- If the scripting variable has a value, store ITS value in the context info instead.
:on error ignore -- Temporarily ignore errors so that accessing a non-existent scripting variable doesn't abort the entire script.
    declare @value as nvarchar(max) = N'$(value)'; -- Try to access the scripting variable; thanks to :on error ignore this will only give a warning.
    if @value <> N'$' + N'(value)' -- Test if there is a value; note the splitting of the reference string to avoid expansion.
    begin
    -- We have a scripting-variable value: Store it in the context info (replacing the default value).
        declare @binValue as varbinary(128) = cast(@value as varbinary(128));
        set CONTEXT_INFO @binValue;
    end
go -- End batch here, so we can switch back to :on error exit (requires a new batch).

:on error exit -- New batch: switch back to robust error handling.
-- End the batch here, so that SSMS in *regular* mode - which will fail on the line above - continues processing below.
-- Note that when run by sqlcmd.exe the subsequent batches will inherit :on error exit.
go

-- Retrieve the value or default value from the context info...
declare @valueOrDefault as nvarchar(max) = convert(nvarchar(max), CONTEXT_INFO(), 0);
-- ... and remove trailing null characters. ?? Is there an easier way to do this?
declare @pos as int = 0;
while @pos < LEN(@valueOrDefault)
begin
    set @pos=@pos+1
    if UNICODE(substring(@valueOrDefault, @pos, 1)) = 0  break;
end
if @pos > 0 set @valueOrDefault = left(@valueOrDefault, @pos - 1);

-- @valueOrDefault now contains the scripting-variable value or default value.
print 'Value or default value: [' + @valueOrDefault + ']';

注意:

sqlcmd.exe当从sqlcmd.exe调用时,以及在常规模式下的SSMS中都可以工作-假设您没有在脚本中使用其他

  • 命令。遗憾的是,SQLCMD模式中的SSMS总是拒绝运行引用了不存在的脚本的脚本,因此需要使用SET CONTEXT_INFO,因为值需要跨批处理边界传递,这不能用T- variable.
  • The变量来完成。要切换回健壮的错误,需要多个批处理。上面的handling.
  • The代码只支持一个脚本变量,并且由于使用了SET CONTEXT_INFO,它的长度被限制为128字节= 64个Unicode字符;不过,也可以使用其他解决方法,例如临时表。
  • 通过有效地将脚本变量转换为常规的T-
  • 变量,您不能在T-SQL需要文字的地方使用该值,例如CREATE DATABASE语句中的数据库名称。
  • 如果未定义脚本变量,则会将以下警告输出到stderr:'variableName‘脚本变量未定义。
票数 6
EN

Stack Overflow用户

发布于 2011-05-04 04:49:45

检索变量并将其赋值给变量,如果该变量未通过SET语句,则将其赋值。catch将处理默认值。这对我来说在SQL Server2005上是有效的。我注意到,当我在SQL Management Studio中运行它时,它总是显示失败,即使我认为它可以工作。当我使用sqlcmd通过命令行运行它时,它可以正常工作,没有任何错误消息。

代码语言:javascript
运行
复制
BEGIN TRY 
    DECLARE @bogusVar VARCHAR(64);
    SET @bogusVar = '' + $(envVar);
    PRINT 'Using values passed from sqlcmd';
END TRY
BEGIN CATCH
    PRINT 'Using default values for script'
    :setvar envVar 'DefaultValue'
END CATCH;
票数 0
EN

Stack Overflow用户

发布于 2012-06-14 01:07:04

如果您从Windows命令提示符运行SQLCMD,请在SQLCMD语句的末尾添加“SQLCMD”。这将消除输出开始时的SQLCMD投诉。

示例: sqlcmd -S DatabaseServer -E -d MyDatabase -i MyScript -v Variable1=Value1 2> nul

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3747006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档