声明标量变量 SQL

Declare scalar variable SQL

我的问题是我想在我的更新查询中使用这个局部变量,有没有办法做到这一点?

 DECLARE @listStr VARCHAR(MAX)
    SELECT @listStr = COALESCE(@listStr+''',''' , '') + cast(int_guid as varchar(max)) 
    FROM ex_in
    SELECT '''' + @listStr + ''''

更新查询

update dbo.ex_in
SET    int_action = CASE WHEN int_action = 120 THEN 110 WHEN int_action = 220 THEN 210 ELSE int_action END
WHERE  int_action IN (120,220)
       AND int_guid in(@listStr)

不,因为字符串变量上的 in 不符合您的预期。

但是,为什么要为变量烦恼呢?只要做:

update dbo.ex_in
    SET int_action = (CASE WHEN int_action = 120 THEN 110 WHEN int_action = 220 THEN 210 ELSE int_action END)
    WHERE int_action IN (120, 220) AND
          int_guid in (SELECT int_guid FROM ex_in);

当然,既然我写了这个,in逻辑就没有必要了,因为两个查询都在同一个table上,没有过滤。只需使用:

update dbo.ex_in
    SET int_action = (CASE WHEN int_action = 120 THEN 110 WHEN int_action = 220 THEN 210 ELSE int_action END)
    WHERE int_action IN (120, 220);

我能想到的做你想做的唯一方法是使用动态 SQL,像这样:

DECLARE @sql varchar(MAX);

SET @sql = '
UPDATE dbo.ex_in
SET    int_action = CASE WHEN int_action = 120 THEN 110 
                         WHEN int_action = 220 THEN 210 
                         ELSE int_action 
                    END;
WHERE  int_action IN (120,220)
       AND int_guid IN (' + @listStr + ')
';

EXEC @sql;