如果sql server中的条件更新查询

时间:2013-09-08 10:06:21

标签: sql sql-server sql-server-2008 stored-procedures

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

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服务器代码是什么?

5 个答案:

答案 0 :(得分:23)

这样的事情应该有效:

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

答案 1 :(得分:18)

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

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

答案 2 :(得分:10)

由于您使用的是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

答案 3 :(得分:3)

这很有效:

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

答案 4 :(得分:0)

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