是否可以将这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
答案 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(condition, whenTrue, whenFalse)
等效于
CASE WHEN condition THEN whenTrue ELSE whenFalse END