是否可以在一个更新语句中全部进行这些sql更新?

时间:2019-05-15 21:13:15

标签: tsql

是否可以将这4个更新合并为一个更新语句?

DECLARE @field_id1 INT = (SELECT field_id FROM t_field WHERE nme = 'first name')
DECLARE @field_id2 INT = (SELECT field_id FROM t_field WHERE nme = 'last name')

UPDATE t_report 
SET grp_field_id = @field_id2
WHERE nme like '%Service report%' and grp_field_id = @field_id1
UPDATE t_report 
SET subgrp_field_id = @field_id2
WHERE nme like '%Service report%' and subgrp_field_id = @field_id1
UPDATE t_report 
SET subsubgrp_field_id = @field_id2
WHERE nme like '%Service report%' and subsubgrp_field_id = @field_id1
UPDATE t_report 
SET subsubsubgrp_field_id = @field_id2
WHERE nme like '%Service report%' and subsubsubgrp_field_id = @field_id1

1 个答案:

答案 0 :(得分:0)

这是我的写法:

DECLARE @field_id1 INT = (SELECT field_id FROM t_field WHERE nme = 'first name')
DECLARE @field_id2 INT = (SELECT field_id FROM t_field WHERE nme = 'last name')

UPDATE t_report 
SET grp_field_id = IIF(grp_field_id = @field_id1, @field_id2, grp_field_id),
    subgrp_field_id = IIF(subgrp_field_id = @field_id1, @field_id2, subgrp_field_id),
    subsubgrp_field_id = IIF(subsubgrp_field_id = @field_id1, @field_id2, subsubgrp_field_id),
    subsubsubgrp_field_id = IIF(subsubsubgrp_field_id = @field_id1, @field_id2, subsubsubgrp_field_id),
WHERE nme LIKE '%Service report%' 
AND @field_id1 IN(grp_field_id, subgrp_field_id, subsubgrp_field_id, subsubsubgrp_field_id)

IIF是简单CASE表达的语法糖-

IIF(condition, whenTrue, whenFalse) 

等效于

CASE WHEN condition THEN whenTrue ELSE whenFalse END