表结果自己 随便定义
------解决方案--------------------
部门人数的增减
--------创建表
create table t(部门 varchar(1000),员工 varchar(1000))
insert into t
select 'personal ', 'wang '
union
select 'personal ', 'zhang '
union
select 'personal ', 'li '
union
select 'finances ', 'zhang '
union
select 'finances ', 'sun '
union
select 'finances ', 'qian '
---------------写触发器
if exists(select name from sysobjects
where name = 'TestTrigger '
and type = 'TR ')
drop Trigger TestTrigger
go
create Trigger TestTrigger
on dbo.t
for delete, insert ,update
as
if ( (select count(1) from deleted) = 0) --insert 新增
begin
---人数统计
select count(1) as 人数,部门
from t
group by 部门
end
else
if ( (select count(1) from inserted) = 0) --delete 减员
begin
---人数统计
select count(1) as 人数,部门
from t
group by 部门
end
else
---------部门调整
begin
---人数统计
select count(1) as 人数,部门
from t
group by 部门
end
go
--------------------------测试
select * from t
---result
部门 员工
finances qian
finances sun
finances zhang
personal li
personal wang
personal zhang
(6 件処理されました)
------------test insert
insert into t
select 'jinnji ', 'liu '
select * from t
-----------result
人数 部门
3 finances
1 jinnji
3 personal
(3 件処理されました)
(1 件処理されました)
部门 员工
finances qian
finances sun
finances zhang
personal li
personal wang
personal zhang
jinnji liu
(7 件処理されました)
------------test delete
delete from t
where 部门 = 'jinnji '
select * from t
-----------result
人数 部门
3 finances
3 personal
(2 件処理されました)
(1 件処理されました)
部门 员工
finances qian
finances sun
finances zhang
personal li
personal wang
personal zhang
----------------test update
update t
set 部门= 'jinnji '
where 员工= 'qian '
select * from t
-----------result
数 部门
2 finances
1 jinnji
3 personal
(3 件処理されました)
(1 件処理されました)
部门 员工
jinnji qian
finances sun
finances zhang
personal li
personal wang
personal zhang
(6 件処理されました)