在视图上建立触发器的方法详解

对视图建立触发器,SQL Server 2000提供了instead of 方法,可以对原触发行为进行改写。
这里以一个简单的例子来说明使用对视图建立触发器的方法:
1. 创建两个Table (假设id唯一)
    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')
    
 数据变化情况如下:

viewTest test1 test2
id name1 name2 id name id name
1 aaa bbb 1 aaa 1 bbb
999 999

对视图进行insert操作
insert into viewTest(id, name1, name2) values('2', 'ccc', 'ddd')
viewTest test1 test2
id name1 name2 id name id name
1 aaa bbb 1 aaa 1 bbb
2 ccc ddd 2 ccc 999 999
2 ddd

对视图进行update操作
1. 修改id字段的数据
update viewtest set id = '11' where id = '1'
viewTest test1 test2
id name1 name2 id name id name
11 aaa bbb 11 aaa 11 bbb
2 ccc ddd 2 ccc 999 999
2 ddd

2. 修改name1字段的数据
update viewTest set name1 = 'updateName1' where id = '11'
viewTest test1 test2
id name1 name2 id name id name
11 updateName1 bbb 11 updateName1 11 bbb
2 ccc ddd 2 ccc 999 999
2 ddd


3.修改name2字段的数据
update viewTest set name2 = 'updateName2' where id = '11'
viewTest test1 test2
id name1 name2 id name id name
11 updateName1 updateName2 11 updateName1 11 updateName2
2 ccc ddd 2 ccc 999 999
2 ddd

对视图进行delete操作
delete viewtest where id = '2'
viewTest test1 test2
id name1 name2 id name id name
11 updateName1 updateName2 11 updateName1 11 updateName2
999 999

由上数据变化可知,update操作实际上是先进行delete, 再进行insert操作。
现在大家应该都清楚了吧,休息一下,呵呵.....

posted on 2008-03-14 16:11  方伍  阅读(5790)  评论(7编辑  收藏  举报