【问题标题】:How to set value to variable using 'exec' in sql如何在sql中使用'exec'将值设置为变量
【发布时间】:2016-07-19 18:43:13
【问题描述】:
declare @tags1 varchar(max)
declare @blockcount int
declare @blockstring varchar(max)
set @tags1='%Gifts%' Or CategoryTag Like'%Packaging%'
set @blockstring= 'SELECT @blogcount=count(*)  FROM M_PHBLogs where CategoryTag LIKE '+ @tags1 +' AND ContentType=1 '
exec (@blockstring) 

我想将 exec(@blockstring) 的结果存储到另一个变量中,例如

@blockcount=exec(@blockstring)
if(@blockcount!=0)
BEGIN
    //something
END

【问题讨论】:

标签: sql sql-server


【解决方案1】:

使用sp_executesql。事实上,你应该总是使用这个函数,因为它允许参数化。

declare @tags1 varchar(max);
declare @blockcount int;
declare @blockstring varchar(max);

set @tags1 = '''%Gifts%'' Or CategoryTag Like ''%Packaging%''';
set @blockstring= 'SELECT @blogcount = count(*) FROM M_PHBLogs where CategoryTag LIKE '+ @tags1 +' AND ContentType = 1';

exec sp_executesql @blockstring, N'@blockcount int output', @blockcount = @blockcount;

【讨论】:

    【解决方案2】:

    使用sp_executesql 记得declare @blockstring nvarchar(max)

    这样称呼:

    exec sp_executesql @blockstring, N'@blogcount int output', @blogcount = @blockcount OUTPUT;
    select @blockcount
    

    【讨论】:

      【解决方案3】:

      不使用 EXEC(据我所知),但使用 sp_ExecuteSQL 您可以定义参数并将这些参数作为输入或输出传递给动态创建的 SQL 脚本

      这是您的 SQL 脚本的简化版本

      declare @tags1 nvarchar(max)
      declare @blockcount int
      declare @blockstring nvarchar(max)
      
      declare @blogcount_out int;
      set @blockstring= 'SELECT @blogcount = count(*) FROM UserDocuments'
      EXECUTE sp_executesql @blockstring, N'@blogcount int output', @blogcount = @blogcount_out output
      select @blogcount_out
      

      请阅读教程Use sp_ExecuteSQL T-SQL Stored Procedure with Input and Output Parameters 以获取有关如何将参数与 sp_executesql 一起使用的更详细示例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-21
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        • 2011-09-03
        • 2021-04-03
        • 1970-01-01
        相关资源
        最近更新 更多