同一个存储过程中,不能多次select into 到同一张表的问题

本文探讨了SQL存储过程中选择性插入临时表的问题,并提供了几种优化策略,包括使用第一种方式、偷懒的方法、动态SQL及将不同功能分开成独立存储过程的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

表记录的插入方式有两种。其一,先create table 再 insert into from ...。其二, 直接 select into。

第一种方式,由于要记录日志,因此IO消耗更多,duration 更长。一般来说能用 select into 的,就尽量不要用 insert into的方式。

有时,存储过程中会需要,根据不同的条件,从不同的表中获取数据放入一个临时表。看起来,这样就需要在不同的分支语句中,写多个对同一张的 select into 语句。

例如:

    if (@b=1)

    begin

         select  a.id, a.name, b.price

          into #temp

          from A inner join B on (a.id=b.id)

    end else if (@b=2)

    begin

         select  d.id, d.name, c.price

          into #temp

          from D inner join C on (d.id=c.id)

    end 

但创建存储过程时会报错,说 #temp 表已经存在。

怎么解决呢?

方法一:用第一种方式,问题是性能差;

方法二:偷懒一些,但性能更好的方法

         select  a.id, a.name, b.price

          into #tempA

          from A inner join B on (@b=1 and a.id=b.id)

         where @b=1


         select  d.id, d.name, c.price

          into #tempB

          from D inner join C on (@b=2 and d.id=c.id)

          where @b=2


         select *

         into #temp

         from ( select * from #tempA union all select * from #tempB )

方法三:用动态sql的办法,把所有的语句都拼接好。好处是性能比方法二好,但缺点也很明显,可读性不强;

方法四:其实,不同的功能,还是最好分成不同的存储过程,优化,维护都更简单。


不知道有没有更好的方式?



  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值