标题: SQL SERVER的行式触发器
ljjk5
元帅
Rank: 1


荣誉会员奖章
UID 46706
精华 1
积分 99426
帖子 49690
威望 554
金币 48489
热心 505
阅读权限 100
注册 2007-2-25
状态 离线
SQL SERVER的行式触发器

曾经以为SQL SERVER的触发器只能触发单行,也就是说如果一个delete触发器,如果同时删除多行时,只会对第一条记录触发,后来发现了不是人家SQL SERVER不支持,而是偶脑子笨没发现。

其实inserted和deleted两张内部表存放了所有要插入或要删除的记录,可以用cursor逐次访问里面的每条记录,下面是一个示例,该触发器将要删除的记录转移到另一张表中:

第一步,创建这两张表

create table table1([id] int primary key, [value] varchar(100))create table table2([id] int primary key, [value] varchar(100))
第二步,插入测试数据

declare @i intset @i = 1while @i <= 100begin    insert into table1([id], [value])    values(@i, cast(@i as varchar))    set @i = @i + 1end
创建table1的delete触发器

create trigger tr_d_table1 on table1 for deleteasbegin    declare @id int, @value varchar(100)    declare cur_del cursor local forward_only for    select [id], [value]    from deleted    open cur_del    fetch next from cur_del into @id, @value    while @@fetch_status = 0    begin        insert into table2([id], [value])        values(@id, @value)            fetch next from cur_del into @id, @value    end    close cur_del    deallocate cur_del    end
现在对table1执行delete语句,发现所有被删除的记录都记录在在table2中了


delete from table1

网友 ljjk5 签名 - 网友社区 ===
顶部
[广告] 免费域名(Free Subdomain) 免费空间(Free hosting) PR查询(Google Pagerank)



当前时区 GMT+8, 现在时间是 2008-10-13 05:35
信产部ICP备案:京ICP备05066424号 北京市公安局网监备案:1101050648号

Powered by Discuz! 5.5.0
清除 Cookies - 联系我们 - 网友俱乐部 - Archiver - WAP