日期:2014-05-18  浏览次数:20749 次

触发器优化
刚才您解答我一个问题,就是http://topic.csdn.net/u/20080518/11/6dd3ebf5-79dd-4208-a127-e6ad05ebcee3.html这里这个,我还有一个问题想问一下,看看有没有解决方法。

aaa(id ,other)
如果删除aaa表内的数据同时激活delete触发器,向ccc(bh,id,other)表内插入已删除的数据,
ccc表字段增加一个bh(编号)字段,bh不是自动增加
目前的逻辑是:我需要先取得ccc里面bh最大值 ,然后从aaa触发器deleted表内逐条取出,让bh+1 增加至ccc 
加入16000条,要执行5分钟左右,有大量得io操作。)
触发器的大致代码如下

SQL code
declare @maxcount int --保存ccc表内 bh 最大值
declare @countnum int --保存需要插入的数据一共多少条
decalre @current int --保存当前插入第几条

set @current =1
set @countnum=0
set @maxcount=(select top 1 bh from ccc order by bh desc)--取得ccc内 bh 最大值
--ccc表可能为空值所以要判断
if @maxcount is null
set @maxcount=0

select dataid=indentity(int,1,1),* into #tempccc from deleted --建立临时表,含有自动编号

set @countnum=(select count(1) from #tempccc) --取得一共需要插入ccc内几条数据

while @current <= @countnum --当前插入编号 小于最大编号
begin
set @maxcount=@maxcount+1 --ccc内 bh 最大值+1

insert into ccc(bh,id,other) select @maxcount,id,other from #tempjsxxb where dateid=@current  --把当前的一条数据插入ccc bh用cc内最大值+1 

set @current=@current +1  --当前编号+1
end

drop table #tempjsxxb


以上是触发器简化的流程,主要目的就是为了删除aaa内数据同时给ccc内增加数据并且bh每次要增加1
在执行时候速度比较慢,所以请问下有没有别的改善方法?

能不能循环时候不让更新,一次更新几百条?会不会快点?
或者采取别的什么方法?


------解决方案--------------------
先看看
------解决方案--------------------
SQL code
declare @maxcount int --保存ccc表内 bh 最大值

set @maxcount=(select top 1 bh from ccc order by bh desc)--取得ccc内 bh 最大值

select dataid=indentity(int,1,1),* into #tempccc from deleted --建立临时表,含有自动编号

insert into ccc(bh,id,other) select isnull(@maxcount,0)+dataid,id,other from #tempjsxxb

------解决方案--------------------
没必要循环插入,你将@maxcount当成dataid的一个偏移量就是,一次插入。
------解决方案--------------------
ccc表字段增加一个bh(编号)字段,bh不是自动增加
---------------
你把这个字段设置成自动增加,那更简单,直接:

insert into ccc(id,other) select id,other from deleted
------解决方案--------------------
SQL code
create table #ccc (bh int)

select top 3 dataid=identity(int,1,1) into #1 from syscolumns
select top 4 dataid=identity(int,1,1) into #2 from syscolumns


declare @maxcount int --保存ccc表内 bh 最大值
set @maxcount=(select top 1 bh from #ccc order by bh desc)--取得ccc内 bh 最大值
insert #ccc select isnull(@maxcount,0)+dataid from #1
select * from #ccc
/*
bh
-----------
1
2
3
*/
go

declare @maxcount int --保存ccc表内 bh 最大值
set @maxcount=(select top 1 bh from #ccc order by bh desc)--取得ccc内 bh 最大值
insert #ccc select isnull(@maxcount,0)+dataid from #2
select * from #ccc
/*
bh
-----------
1
2
3
4
5
6
7
*/
go

drop table #ccc,#1,#2

------解决方案--------------------
探讨
太帅了,Limpire 太崇拜你了,果然是这样的。。。。。。感激之情不知道怎么表达了~~谢谢谢谢 果然变了,,,^_^
太感谢了。。。^_^呆会分数奉上,我先改改代码 啊哈