我一直在研究,但似乎无法得到正确的结果。 我有下表:
create table school_tb
(idSchool int identity primary key,
nameSchool varchar(100),
schoolPopulation int
)
create table career_tb
(idCareer int identity primary key,
nameCareer varchar(100),
carrerPopulation int,
numberClasses int,
idSchool int foreign key references school_tb(idSchool)
)
为了找出第一个表中的人口数量,我必须对同一学校的职业人口进行 SUM() 计算。 我需要创建一个触发器,当我更新 Career_tb 中的人口时,该触发器将更新表 school_tb 中的人口列。请帮我。 我有类似的东西,但我无法让它工作。
--create trigger updatePopulation
--on career_tb
--for update as
--if UPDATE(carrerPopulation)
--update school_tb set schoolPopulation =(SELECT add(carrerPopulation)
-- from career_tb
-- where idSchool=(SELECT idSchool
-- from career_tb
-- where idCareer=@idCareer)
-- )
--go
我很感激所提供的任何帮助。谢谢
最佳答案
这应该可以帮助你。请参阅触发器正文内的注释。
create trigger updatePopulation
on career_tb
-- to update sum even if carreer gets deleted or inserted
after insert, update, delete
as
-- to avoid trigger messing up rows affected
set nocount on
if UPDATE(carrerPopulation)
begin
-- update sum by difference between previous and current state of one record in career
update school_tb
set schoolPopulation = schoolPopulation + difference
from school_tb
-- derived table sums all the careers changed in one go
inner join
(
-- sum all values from careers by school
select idSchool, sum (carrerPopulation) difference
from
(
-- change sign of previous values
select deleted.idSchool, -deleted.carrerPopulation carrerPopulation
from deleted
union all
-- + current values
select inserted.idSchool, inserted.carrerPopulation
from inserted
) a
group by idSchool
-- Skip update in case of no change
having sum (carrerPopulation) <> 0
) a
on school_tb.idSchool = a.idSchool
end
关于sql - sql server 2008中的触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9860467/