3

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

这是关系模式:

  • PaperInvolvement( paperNr, academicId, paperRole)
  • Academic( academicId, 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

我的问题是,根据要求(我在项目符号列表中列出的内容),这是回答问题的正确方法吗?

4

1 回答 1

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
于 2012-12-05T17:52:45.087 回答