【问题标题】:optimize the stored procedure with优化存储过程
【发布时间】:2021-04-17 02:55:09
【问题描述】:

我想通过摆脱对同一子查询的 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
)

【问题讨论】:

    标签: sql sql-server stored-procedures subquery temp-tables


    【解决方案1】:

    我实际上建议将其表述为:

    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 语句,因此它们在代码中只包含一次。

    【讨论】:

      【解决方案2】:

      如果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)
      

      【讨论】:

        【解决方案3】:

        可能的解决方案是

        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
        

        【讨论】:

          【解决方案4】:

          我建议使用左连接执行更新:

          UPDATE t1
            SET t1.status = t2.status
            FROM some_table t1
            LEFT JOIN other_table t2 ON t2.Id = t1.Id
          

          【讨论】:

            猜你喜欢
            • 2012-02-26
            • 2018-04-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多