rainbowzc

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

 

昨日一朋友发来一段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

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

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


 

 

////
 可将函数和变量声明为 table 类型。table 变量可用于函数、存储过程和批处理中。

尽可能使用表变量而不使用临时表。table 变量有以下优点:

table 变量的行为类似于局部变量,有明确定义的作用域。该作用域为声明该变量的函数、存储过程或批处理。
在其作用域内,table 变量可像常规表那样使用。该变量可应用于 SELECT、INSERT、UPDATE 和 DELETE 语句中用到表或表的表达式的地方。但是,table 不能用在下列语句中:

INSERT INTO table_variable EXEC 存储过程。

SELECT select_list INTO table_variable 语句。

在定义 table 变量的函数、存储过程或批处理结束时,自动清除 table 变量。

在存储过程中使用表变量与使用临时表相比,减少了存储过程的重新编译量。


涉及表变量的事务只在表变量更新期间存在。这样就减少了表变量对锁定和记录资源的需求。
不支持在表变量之间进行赋值操作。另外,由于表变量作用域有限,并且不是持久数据库的一部分,因而不受事务回滚的影响。

////

 

如果数据量不是很大的话(十万级),查询的时间两者差不多。差个1,2s,对于节约了10,20s来说,不算什么了。
具体情况具体分析。
我朋友使用以上方式优化之后,其他什么也没改,比没有优化之前节约了近一半的时间。
@WEBBER
这个具体情况具体分析,变量表的好像就如c#中的局部变量,所以生命周期短,但并不是说一定比临时表优。
临时表需要自己去清除其资源占用。

posted on 2010-08-20 19:24  ct  阅读(1086)  评论(0编辑  收藏  举报