SQL Server 触发器初级应用问题
表:
A (ID,Avalue)
B (ID,AID,Bvalue) 注:AID为A表ID的外键
视图:
create view AB_view
as
select AAA.*, BBB.Bvalue from AAA join BBB on (AAA.ID = BBB.AID)
触发器:
alter trigger AB_tr on AB_view instead of insert
as
begin
//这里不知道要怎么写,先将Avalue插入A表,
//在将A表的ID和Bvalue插入B表的AID和Bvalue
end
插入操作:
insert into AB_view (Avalue, Bvalue) values ('A3', 'B3')
//对视图插入,更新到A表和B表
[解决办法]
做了一个实验,你看看:
/*
drop table a
drop table b
go
*/
create table A(ID int identity(1,1) primary key,Avalue varchar(10))
create table B(ID int identity(1,1) primary key,AID int,Bvalue varchar(10))
go
/*
drop view AB_view
go
*/
create view AB_view
as
select A.*, B.Bvalue from A join B on (A.ID = B.AID)
go
--drop trigger AB_tr on AB_view
create trigger AB_tr on AB_view instead of insert
as
begin
insert into a(Avalue)
select Avalue
from
(
select distinct id,Avalue
from inserted i
)t
insert into b(aid,Bvalue)
select scope_identity(),Bvalue
from inserted i
end
go
insert into AB_view (Avalue, Bvalue) values ('A3', 'B3')
select * from a
/*
IDAvalue
1A3
*/
select * from b
/*
IDAIDBvalue
11B3
*/
create table A(ID int identity(1,1),Avalue varchar(15))
create table B(ID int identity(1,1),AID int,Bvalue varchar(15))
create view AB_view
as
select A.*,B.Bvalue from A join B on A.ID=B.AID
create trigger AB_tr on AB_view
instead of insert
as
begin
declare @ta table(ID int)
insert into A(Avalue)
output inserted.ID into @ta
select Avalue from inserted
insert into B(AID,Bvalue)
select (select ID from @ta),(select Bvalue from inserted)
end
-- 插入操作
insert into AB_view(Avalue,Bvalue) values('A3','B3')
-- 结果
select * from A
/*
ID Avalue
----------- ---------------
1 A3
(1 row(s) affected)
*/
select * from B
/*
ID AID Bvalue
----------- ----------- ---------------
1 1 B3
(1 row(s) affected)
*/