触发2个表

时间:2012-12-05 07:30:38

标签: sql sql-server triggers

这是一个家庭作业问题,只是为了说清楚。

这是关系模式:

  • PaperInvolvementpaperNr, academicId, paperRole
  • AcademicacademicId, acadName, employer

因此(academicID)Academic的主键,而(paperNr, academicId)PaperInvolvement表的主键。

这是我被要求做的触发器:

  • 插入后PaperInvolvement,更新
  • 更新后Academic
  • 防止在同一家公司工作的任何2名学者参与相同角色的同一篇论文。
  • 使用存储过程或完全覆盖触发器

此表格中只有2个角色,ReviewerAuthor

这是我到目前为止所做的:

CREATE TRIGGER TR_PaperInvolvement_1
ON PaperInvolvement
AFTER INSERT, UPDATE
AS
IF EXISTS
(
SELECT a.academicId, paperRole, paperNr
FROM
(SELECT academicId
FROM Academic
GROUP BY employer, academicId) AS a
JOIN
(SELECT academicId, paperRole, paperNr
FROM PaperInvolvement

GROUP BY paperNr, academicId, paperRole) AS p_inv
ON a.academicId = p_inv.academicId
WHERE paperRole = 'Author' AND paperRole = 'Reviewer'

)
BEGIN
RAISERROR('Cannot have 2 Academics from the same company to work on
different roles for this paper.',16,1)
ROLLBACK TRANSACTION
END
GO

我的问题是,基于要求(我在子弹列表中列出的内容),这是回答问题的正确方法吗?

1 个答案:

答案 0 :(得分:1)

试试这个

CREATE TRIGGER TR_PaperInvolvement_Modify
ON PaperInvolvement
AFTER INSERT, UPDATE
AS
begin
    if exists
    (
        select P.paperNr, A.employer
        from PaperInvolvement as P   
            inner join Academic as A on A.academicID = P.academicID 
        where P.paperNr in (select i.paperNr from inserted as i)
        group by P.paperNr, A.employer
        having
            count(case when P.paperRole = 'Author' then 1 end) > 0 and
            count(case when P.paperRole = 'Reviewer' then 1 end) > 0
    )
    begin
        raiserror('Cannot have 2 Academics from the same company to work on different roles for this paper.', 16, 1)
        rollback transaction 
    end
end