这里有一个SQL:
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;
有什么方法可以让它更简单或更干净吗?
2条答案
按热度按时间holgip5t1#
我们可以在同一个
update
语句中将其重写为all run,其中它为WHERE
子句中匹配的每个id设置所有列,并在每个列上使用case
表达式来决定设置相同的值或新值:我们可以进一步将其更改为在table-valued constructor上使用
JOIN
表达式:这两种方法都有自动确保所有内容都在同一事务中的优点(更好的原子性,如果这是一个词的话),我喜欢第二种选择--尽管它的代码有点多--因为它将新值更像数据一样对待。
但是
我不会把它们称为“更简单”或“更干净”,你已经拥有的东西在这方面可能已经足够好了,除非你真的想要单一语句的好处。
holgip5t2#
使用参数创建一个函数或触发器。如果你有一个列列表要设置,一个列列表要检查,将数组作为参数传递给函数,并使用循环而不是像下面这样使用一个语句来构建字符串。在这个例子中,我只是为每一个变量而不是函数中的参数(作为变量)。
然后像这样使用动态SQL。
或
调用函数: