sql - sql server 2008中的触发器

标签 sql sql-server-2008 triggers

我一直在研究,但似乎无法得到正确的结果。 我有下表:

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/

相关文章:

.net - SSIS DataFlow 随着时间的推移显着减慢

mysql - 没有自动递增 PK 的最后插入行信息

triggers - Quartz.NET - 在一天中的特定时间触发

sql - 运行计数不同

sql - 如何修复sql中的 "ORA-02270: no matching unique or primary key for this column-list "错误

c# - 如何优化 linq 中将 ~4000 行转换到对象的 "select all"语句?

sql - 更改要计算的列 SQL SERVER

SQL:指定列的冗余 WHERE 子句 > 0?

sql - 在 SQL 表条目中使用通配符

mysql - 为两个表创建了 TRIGGER 但收到错误消息