简体   繁体   中英

query: if condition in sql server update

I have a SQL server table in which there are 2 columns that I want to update either of their values according to a flag sent to the stored procedure along with the new value, something like:

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

What is the correct SQL server code to do so??

I thought M.Ali's comment was correct, so I've constructed this based on his suggestion. I'm also assuming the status field is 'approved' or 'declined' as you say based on if it's populated or not. If there are any other conditions on the status field, offcourse you must add these to you where statements

BEGIN TRANSACTION

Update Payment
set post_date = new_postdate_value
account_num = new_account_num_value
pay_am = new_pay_am_value
pay_type = new_pay_type_value
authoriz = new_authoriz_value
where status is not null

UPDATE Payment
SET account_num = new_account_num_value
WHERE status is null

COMMIT TRANSACTION

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM