create table a_1
(
[id] char (20),
total int
)
create table a_2
(
[id] char (20),
total int
)
有以上兩表。
寫一個(gè)觸發(fā)器,實(shí)現(xiàn):
對a_1進(jìn)行insert,在a_2中,如果存在和a_1中剛插入的id相同的id,則對a_2中的這個(gè)id相應(yīng)的total進(jìn)行累加,如果沒有,則在a_2中插入a_1中新插入的字段
對a_1進(jìn)行delete,則在a_2中相同的id相應(yīng)的total上減去a_1中剛刪除的那個(gè)total
假設(shè)a_1為:
001 10
002 8
003 7
001 2
004 90
002 3
001 22
a_2為:
001 34
002 11
003 7
004 90
insert:
insert a_1 values('001',100)
insert后:
a_1為:
001 10
002 8
003 7
001 2
004 90
002 3
001 22
001 100
a_2為:
001 134
002 11
003 7
004 90
delete:
delete a_1
where a_1.[id]='001' and a_1.total = 10
delete后:
a_1為:
002 8
003 7
001 2
004 90
002 3
001 22
001 100
a_2為:
001 124
002 11
003 7
004 90
code:
create table a_1
(
[id] char (20),
total int
)

create table a_2
(
[id] char (20),
total int
)


create trigger trigger_1
on a_1
for insert , delete
as
if exists (select * from inserted) -- 判斷是否進(jìn)行insert操作
begin
if exists
(
select 'true'
from inserted
join a_2 on inserted.[id] =a_2.[id]
)
begin
declare @id_1 char(20),@val_1 int
select @id_1 = [id] , @val_1 = total from inserted

update a_2
set a_2.total = a_2.total + @val_1
where @id_1 = a_2.[id]
end
else
begin
declare @id_2 char(20),@val_2 int
select @id_2 = [id] , @val_2 = total from inserted

insert a_2 values(@id_2, @val_2)
end
end

else -- delete操作

begin

declare @id_3 char(20) , @val_3 int
select @id_3 = [id] , @val_3 = total from deleted

update a_2
set a_2.total = a_2.total - @val_3
where @id_3 = a_2.[id]

end

select * from a_1
select * from a_2

insert a_1 values('001',10)
insert a_1 values('002',9)
insert a_1 values('001',40)
insert a_1 values('003',73)
insert a_1 values('002',11)

select * from a_1
select * from a_2

delete a_1
where a_1."id" = '001' and a_1.total = 10

select * from a_1
select * from a_2
第一次寫觸發(fā)器,不免方法較笨,如果誰有更好的方法,還望分享分享。
posted on 2009-11-25 19:57
zhaoyg 閱讀(235)
評論(0) 編輯 收藏 引用 所屬分類:
SQL Server學(xué)習(xí)筆記