sql server 存储过程的优化.(变量表,临时表的简单分析)
发布日期:2021-05-09 01:24:00 浏览次数:19 分类:博客文章

本文共 1084 字,大约阅读时间需要 3 分钟。

昨日一朋友发来一段sql的存储过程(如下),让我看看能不能优化一下。
insert @T1
  select g_no,co_no,si_no,str_no,sum(ind_qty) as qty
  from instock_detail where  in_id = @id  group by g_no,co_no,si_no,str_no
  
  --?unitstock  -->保存在变量表中 
  insert @T2
  select a.*  
  from  unitstock a,@T1 b
  where a.g_no =b.g_no  and a.co_no =b.co_no  
  and a.si_no =b.si_no and a.str_no=b.str_no 
 
  delete unitstock
  from @T1 a
  where unitstock.g_no=a.g_no  and unitstock.co_no =a.co_no    
  and unitstock.si_no=a.si_no and unitstock.str_no=a.str_no  
  
  insert unitstock
  select g_no,co_no,si_no,str_no,sum(qty) as qty  from
  ( select  * from @T1   union all select * from @T2 
  ) AA
  group by g_no,co_no,si_no,str_no
今日有空,作了一下变量表,临时表插入数据的性能分析。
1。变量表:

declare @t table

(
id nvarchar(50),
supno nvarchar(50),
eta datetime
)
insert  @t
select top 10000 id,supno,eta from 表

这一句执行sql需时间:16806ms

2。临时表:
create table #t
(
id nvarchar(50),
supno nvarchar(50),
eta datetime
)
insert #t
select top 10000 id,supno,eta
from 表

这一句执行sql需时间:76ms

3。不创建临时表,直接插入到临时表

select top 10000 id,supno,eta

into #t
from 表

这一句执行sql需时间:30ms

通过以上的分析,可以非常清晰的看出那个优,那个劣了。

以上只是简单的分析了一下。所以在存储过程中尽量合作临时表来存储临时数据,不要使用变量表。

 

上一篇:flash菜单与asp.net进行交互.
下一篇:在IIS与SQL Server 2005中设置,让Reporting Services发布的web报表允许匿名访问

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年05月02日 06时58分17秒