|
|
Posted on
2009-03-05 14:10
杨彬Allen
阅读( 174)
评论()
收藏
举报
 Trigger and View
-- =============================================================================
-- 標題: 試圖view、觸發器Trigger、inserted | deleted表的應用
-- 原創: takako_mu
-- 时间: 2009-02-04
-- 地点: 昆山
-- =============================================================================
 /**//*
Trigger(一)的目的在于保持多表(或表與試圖結合)之間資料的一致性。
*/
 /**//*
關于deleted和inserted:
inserted 和 deleted 表主要用于触发器中:①扩展表间引用完整性。
②在以视图为基础的基表中插入或更新数据。
③检查错误并基于错误采取行动。

deleted 表用于存储 delete 和 update 语句所影响的行的复本。
在执行 delete 或 update 语句时,行从触发器表中删除,并传输到 deleted 表中。

inserted 表用于存储 insert 和 update 语句所影响的行的复本。
在一个插入或更新事务处理中,新建行被同时添加到 inserted 表和触发器表中。
inserted 表中的行是触发器表中新行的复本。

updated 表: Sorry,并不存在這樣的表o(∩_∩)o
update似于在 delete 之后执行 insert。
首先旧行被复制到 deleted 表中,然后新行被复制到触发器表和 inserted 表中。
*/
if not object_id('tempa') is null drop table tempa
create table tempa(uid int identity(1,1) not null primary key,department nvarchar(10),uname nvarchar(15))
insert tempa
select 'IT-SCM','Michelle_Chien' union all
select 'IT-SCM','Alen_Fan' union all
select 'IT-SCM','Takako_Yang'

if not object_id('tempb') is null drop table tempb
create table tempb(uid int identity(1,1) not null primary key,department nvarchar(10),uname nvarchar(15))
insert tempb
select 'IT-ERP','JeffL_Lai' union all
select 'IT-ERP','Ike_Li'
go


--drop view tempview
create view tempview
as
select row_number() over(order by A.department,A.uname) as num,A.* from(
select department,uname from tempa union all
select department,uname from tempb
)as A
--select * from tempview
go

--drop trigger Tr_temp
create trigger Tr_temp on tempview
instead of update
as
begin
delete tempa where checksum(department,uname) in ( select checksum(department,uname) from deleted)
delete tempb where checksum(department,uname) in ( select checksum(department,uname) from deleted)
insert tempa select department,uname from inserted where department='IT-SCM'
insert tempb select department,uname from inserted where department='IT-ERP'
end
go

update tempview set uname='Takako_mu' where uname='Takako_Yang'

select * from tempa

--uid department uname
------------- ---------- ---------------
--1 IT-SCM Michelle_Chien
--2 IT-SCM Alen_Fan
--4 IT-SCM Takako_mu

--(3 個資料列受到影響)
|