Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for If not null,then update or else keep the same data

I am having a table which has about 17 fields. I need to perform frequent updates in this table. But the issue is each time I may be updating only a few fields. Whats the best way to write a query for updating in such a scenario? I am looking for an option in which the value gets updated only if it is not null.

For example I have four fields in database Say A,B,C,D. User updates the value of say D. All other values remains the same. So I want an update query which updates only the value of D keeping the others unaltered. SO if i put a,b and c as null and d with the value supplied by user I want to write an update query which only updates the value of d as a,b and c is null. MsSQL 2012 is my database

like image 754
Selvakesavan Thiyagarajan Avatar asked Mar 03 '26 08:03

Selvakesavan Thiyagarajan


2 Answers

May be something like this

Update T
SET A = CASE WHEN A IS NOT NULL THEN 'Value' ELSE A END,
    B = CASE WHEN B IS NOT NULL THEN 'Value' ELSE B END,
    C = CASE WHEN C IS NOT NULL THEN 'Value' ELSE C END
    D = CASE WHEN D IS NOT NULL THEN 'Value' ELSE D END
FROM Table1 T
like image 186
Vignesh Kumar A Avatar answered Mar 05 '26 23:03

Vignesh Kumar A


If you are calling this from an application, the easiest way is to just run the query that you want:

update t
    set d = @d
    where id = @id;

If you want a generic statement, then you can use:

update t
    set a = coalesce(@a, a),
        b = coalesce(@b, b),
        c = coalesce(@c, c),
        d = coalesce(@d, d)
    where id = @id;
like image 36
Gordon Linoff Avatar answered Mar 05 '26 23:03

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!