读书人

熟悉触发器的请近一个有一点复杂的更

发布时间: 2012-01-18 00:23:26 作者: rapoo

熟悉触发器的请近,一个有一点复杂的更新插入触发器
create table t1 (name varchar(50),unit varchar(50),class varchar(50))
-- class 就只有3种(差,合格,优秀)
insert t1
select 'a ' , '1班 ', '优秀 ' union all
select 'a ', '1班 ', '合格 ' union all
select 'a ', '1班 ', '较差 ' union all
select 'a ', '2班 ', '优秀 'union all
select 'a ', '2班 ', '优秀 'union all
select 'a ', '2班 ', '合格 ' union all

select 'b ' , '1班 ', '优秀 ' union all
select 'b ', '1班 ', '合格 ' union all
select 'b ', '1班 ', '较差 ' union all
select 'b ', '2班 ', '优秀 'union all
select 'b ', '2班 ', '优秀 'union all
select 'b ', '2班 ', '合格 '


表t2完全是根据表t1 得到的 以上会得到如下的t2 ,otherthing列除外

create table t2 (name varchar(50),unit varchar(50),较差 int ,合格 int ,优秀 int ,otherthing varchar(50))
insert t2
select 'a ', '1班 ' ,1,1,1, 'wwfefaafaf ' union all
select 'a ', '2班 ',0,1,2 , 'fdasfdasfd ' union all
select 'b ', '1班 ' ,1,1,1, 'wwewew ' union all
select 'b ', '2班 ',0,1,2 , 'eeeeee '


在表t1上定义个触发器,想得到一个汇总更新插入 在t2表也同时变化
比如 更新 t1的第一行数据 ,t2会相应的变化
在t1插入 'a ' , '1班 ', '较差 ' ,t2会有变化
在t1中插入 'c ' , '4班 ', '较差 ' ,t2会有增加一条 'c ' , '4班 ',1,0,0 ,null的行

这样的触发器有点复杂 不过理解起来不难


[解决办法]
create table t1 (name varchar(10),unit varchar(10),class varchar(10))
create table t2 (name varchar(10),unit varchar(10),较差 int ,合格 int ,优秀 int ,otherthing varchar(10))
go
create trigger tr_t1 on t1
for update,delete,insert
as
begin

insert t2(name,unit,较差,合格,优秀)
select distinct name,unit,0,0,0 from inserted _i
where not exists(select 1 from t2 where _i.name = name and _i.unit = unit)

update t2
set t2.较差 = t2.较差 + (select count(1) from inserted where name = t2.name and unit = t2.unit and class = '较差 ')
,t2.合格 = t2.合格 + (select count(1) from inserted where name = t2.name and unit = t2.unit and class = '合格 ')
,t2.优秀 = t2.优秀 + (select count(1) from inserted where name = t2.name and unit = t2.unit and class = '优秀 ')

update t2
set t2.较差 = t2.较差 - (select count(1) from deleted where name = t2.name and unit = t2.unit and class = '较差 ')
,t2.合格 = t2.合格 - (select count(1) from deleted where name = t2.name and unit = t2.unit and class = '合格 ')


,t2.优秀 = t2.优秀 - (select count(1) from deleted where name = t2.name and unit = t2.unit and class = '优秀 ')

delete t2
where 较差+合格+优秀 = 0
end
go
insert t1
select 'a ' , '1班 ', '优秀 ' union all
select 'a ', '1班 ', '合格 ' union all
select 'a ', '1班 ', '较差 ' union all
select 'a ', '2班 ', '优秀 'union all
select 'a ', '2班 ', '优秀 'union all
select 'a ', '2班 ', '合格 ' union all
select 'b ' , '1班 ', '优秀 ' union all
select 'b ', '1班 ', '合格 ' union all
select 'b ', '1班 ', '较差 ' union all
select 'b ', '2班 ', '优秀 'union all
select 'b ', '2班 ', '优秀 'union all
select 'b ', '2班 ', '合格 '

select * from t2
/*
name unit 较差 合格 优秀 otherthing
---------- ---------- ----------- ----------- ----------- ----------
a 1班 1 1 1 NULL
a 2班 0 1 2 NULL
b 1班 1 1 1 NULL
b 2班 0 1 2 NULL

(所影响的行数为 4 行)
*/

drop table t1,t2

读书人网 >SQL Server

热点推荐