T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

后端 未结 6 829
再見小時候
再見小時候 2020-12-02 12:36

I am wondering if this is possible at all. I want to update column x if a condition is true, otherwise column y would be updated

UPDATE table SET
     (CASE          


        
6条回答
  •  时光取名叫无心
    2020-12-02 13:11

    I believe that you can omit updating the "non-desired" columns by adjusting the other answers as follows:
    update table set columnx = (case when condition1 then 25 end), columny = (case when condition2 then 25 end)

    As I understand it, this will update only when the condition is met.

    After reading all the comments, this is the most efficient:
    Update table set ColumnX = 25 where Condition1 Update table set ColumnY = 25 where Condition1

    Sample Table:
    CREATE TABLE [dbo].[tblTest]( [ColX] [int] NULL, [ColY] [int] NULL, [ColConditional] [bit] NULL, [id] [int] IDENTITY(1,1) NOT NULL ) ON [PRIMARY]
    Sample Data:
    Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0) Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0) Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1) Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1) Insert into tblTest (ColX, ColY, ColConditional) values (1, null, null) Insert into tblTest (ColX, ColY, ColConditional) values (2, null, null) Insert into tblTest (ColX, ColY, ColConditional) values (null, 1, null) Insert into tblTest (ColX, ColY, ColConditional) values (null, 2, null)

    Now I assume you can write a conditional that handles nulls. For my example, I am assuming you have written such a conditional that evaluates to True, False or Null. If you need help with this, let me know and I will do my best.

    Now running these two lines of code does infact change X to 25 if and only if ColConditional is True(1) and Y to 25 if and only if ColConditional is False(0)

    Update tblTest set ColX = 25 where ColConditional = 1 Update tblTest set ColY = 25 where ColConditional = 0

    P.S. The null case was never mentioned in the original question or any updates to the question, but as you can see, this very simple answer handles them anyway.

提交回复
热议问题