在视图上建立触发器的方法详解
2010-04-20 14:55:09 阅读9 评论 字号:大中小
http://www.cnblogs.com/binbin1845/archive/2008/03/14/1106054.html
对视图建立触发器,SQL Server 2000提供了instead of 方法,可以对原触发行为进行改写。
这里以一个简单的例子来说明使用对视图建立触发器的方法:
1. 创建两个Table (假设id{wy})
create table test1(id varchar(50), name varchar(50))
create table test2(id varchar(50), name varchar(50))
2. 创建一个视图
create view viewTest as
select test1.id, test1.name as name1, test2.name as name2 from test1 inner join test2 on test1.id = test2.id
3. 创建insert触发器
create trigger triggerInsertViewTest on viewTest
instead of insert
as
begin
insert test1(id, name) select id, name1 from inserted
insert test2(id, name) select id, name2 from inserted
end
4. 创建update触发器
create trigger triggerUpdateViewTest on viewTest
instead of update
as
if update(id)
begin
update test1 set test1.id = inserted.id from test1, inserted, deleted where test1.id = deleted.id
update test2 set test2.id = inserted.id from test2, inserted, deleted where test2.id = deleted.id
end
if update(name1)
begin
update test1 set test1.name = inserted.name1 from test1, inserted where test1.id = inserted.id
end
if update(name2)
begin
update test2 set test2.name = inserted.name2 from test2, inserted where test2.id = inserted.id
end
5. 创建delete触发器
create trigger triggerDeleteViewTest on viewTest
instead of delete
as
begin
delete test1 from test1, deleted where test1.id = deleted.id
delete test2 from test2, deleted where test2.id = deleted.id
end
目前为至,触发器创建好了,现在开始我们来进行测试
创建原始数据
insert into test1 values('1', 'aaa')
insert into test2 values('1', 'bbb')
insert into test2 values('999', '999')
数据变化情况如下:
对视图进行insert操作
insert into viewTest(id, name1, name2) values('2', 'ccc', 'ddd')
对视图进行update操作
1. 修改id字段的数据
update viewtest set id = '11' where id = '1'
2. 修改name1字段的数据
update viewTest set name1 = 'updateName1' where id = '11'
3.修改name2字段的数据
update viewTest set name2 = 'updateName2' where id = '11'
对视图进行delete操作
delete viewtest where id = '2'
由上数据变化可知,update操作实际上是先进行delete, 再进行insert操作。
现在大家应该都清楚了吧,休息一下,呵呵.....