簡體   English   中英

在SQL Server 2008中觸發

[英]trigger in sql server 2008

我一直在研究,但似乎無法正確解決。 我有以下表格:

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)
)

為了在第一張表中找出人口,我必須從同一所學校的職業中求和。 我需要創建一個觸發器,以在更新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
CREATE TRIGGER name ON career_tb
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;

    MERGE school_tb T
    USING
    (
        SELECT idSchool, SUM(carrerPopulation) res
        FROM
        (
            SELECT idSchool, carrerPopulation
            FROM INSERTED
            UNION ALL
            SELECT idSchool, -carrerPopulation
            FROM DELETED
        ) t
        GROUP BY idSchool
    ) S
    ON T.idSchool = S.idSchool
    WHEN MATCHED THEN UPDATE SET
        schoolPopulation = T.schoolPopulation  +S.res
    ;


END

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM