33

我有一个 SQL 服务器表,其中有 2 列我想根据发送到存储过程的标志以及新值来更新它们的任何一个值,例如:

UPDATE
    table_Name

SET
    CASE
        WHEN @flag = '1' THEN column_A += @new_value
        WHEN @flag = '0' THEN column_B += @new_value
    END AS Total

WHERE
    ID = @ID

这样做的正确 SQL 服务器代码是什么?

4

5 回答 5

41

像这样的东西应该工作:

UPDATE
    table_Name
SET 
  column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
  column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
    ID = @ID
于 2013-09-08T10:09:39.860 回答
26

当前的答案很好,应该可以正常工作,但是更简单、更明显、更易于维护的答案有什么问题:

IF @flag = 1
    UPDATE table_name SET column_A = column_A + @new_value WHERE ID = @ID;
ELSE
    UPDATE table_name SET column_B = column_B + @new_value WHERE ID = @ID;

尽管这是一个非常简单的查询,但它更容易阅读。

这是@snyder 提供的一个工作示例:SqlFiddle

于 2013-09-08T10:15:23.857 回答
12

由于您使用的是 SQL 2008:

UPDATE
    table_Name

SET
    column_A  
     = CASE
        WHEN @flag = '1' THEN @new_value
        ELSE 0
    END + column_A,

    column_B  
     = CASE
        WHEN @flag = '0' THEN @new_value
        ELSE 0
    END + column_B 
WHERE
    ID = @ID

如果您使用的是 SQL 2012:

UPDATE
    table_Name
SET
    column_A  = column_A + IIF(@flag = '1', @new_value, 0),
    column_B  = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
    ID = @ID
于 2013-09-08T10:10:42.443 回答
6

这很好用:

UPDATE
    table_Name
SET 
  column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
  column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
    ID = @ID
于 2014-08-17T12:42:14.597 回答
1
DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1  )

UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1
于 2019-07-23T07:06:27.063 回答