如何解决优化存储过程
我想通过消除对同一子查询的 3 次调用来优化以下过程。我以为我可以在存储过程中创建一个临时表并更新它,但不知道该怎么做。欢迎任何其他方式来做到这一点。
update some_table SET
status = (
case when 'OVERDUE' in (select status from other_table temp where Id = temp.Id)
then 'OVERDUE'
when 'UPCOMING' in (select status from other_table temp where Id = temp.Id)
then 'UPCOMING'
when 'PAID' in (select status from other_table temp where Id = temp.Id)
then 'PAID'
else
null
END
)
解决方法
我建议使用左连接执行更新:
UPDATE t1
SET t1.status = t2.status
FROM some_table t1
LEFT JOIN other_table t2 ON t2.Id = t1.Id
,
可能的解决方案是
update s
SET
status = Case temp.Status
when 'OVERDUE'
then 'OVERDUE'
when 'UPCOMING'
then 'UPCOMING'
when 'PAID'
then 'PAID'
else null
END
FROM some_table S LEFT JOIN
other_table temp ON
s.Id = temp.Id
,
如果 other_table temp where Id = temp.Id
中有多个记录,那么您可以使用以下查询:
update some_table SET status =
(select case when count(case when status = 'OVERDUE' then 1 end) > 0 then 'OVERDUE'
when count(case when status = 'UPCOMING' then 1 end) > 0 then 'UPCOMING'
when count(case when status = 'PAID' then 1 end) > 0 then 'PAID'
end
from other_table temp where Id = temp.Id)
,
我实际上建议这样的短语:
update some_table
set status = (select top (1) ot.status
from other_table ot join
(values ('OVERDUE',1),('UPCOMING',2),('PAID',3)
) v(status,ord)
on ot.status = v.status
where ot.id = some_table.id
order by v.ord
);
我不喜欢重复特定的 status
值。这使用了 values
语句,因此它们在代码中只包含一次。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。