I have a sql here:
update table_name
set column1 = new_value1,
column2 = new_value2
where id = 1;
update table_name
set column3 = new_value3,
column4 = new_value4
where id = 3;
update table_name
set column5 = new_value5,
column6 = new_value6,
column7 = new_value7
where id = 6;
Is there anyway I can make it simpler or cleaner ?
2
Answers
Make a function or trigger using parameters. If you have a list of columns to set and a list of where columns to check, pass arrays as parameters to the function, and build the string using a loop instead of using one statement like below. I simply have variables for each in this example rather than parameters (as variables) in a function.
Then use dynamic SQL like so.
or
Calling function:
We could re-write this to all run in the same
update
statement, where it sets all of the columns for each id matched in theWHERE
clause and usescase
expressions on each column to decide to set the same value or a new value:We could further change this to use a
JOIN
expression on a table-valued constructor:Either approach does have the advantage of automatically ensuring everything is inside the same transaction (better atomicity, if that’s even a word), and I like the second option – even though it’s a little more code – for the the way it treats the new values more like data.
… But
I wouldn’t call them any "simpler" or "cleaner". What you have already is probably good enough in that regard, unless you really want the single-statement benefits.