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

后端 未结 6 830
再見小時候
再見小時候 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:10

    You can't use a condition to change the structure of your query, just the data involved. You could do this:

    update table set
        columnx = (case when condition then 25 else columnx end),
        columny = (case when condition then columny else 25 end)
    

    This is semantically the same, but just bear in mind that both columns will always be updated. This probably won't cause you any problems, but if you have a high transactional volume, then this could cause concurrency issues.

    The only way to do specifically what you're asking is to use dynamic SQL. This is, however, something I'd encourage you to stay away from. The solution above will almost certainly be sufficient for what you're after.

提交回复
热议问题