这是一个家庭作业问题,只是为了说清楚。
这是关系模式:
PaperInvolvement
(paperNr, academicId, paperRole
)Academic
(academicId, acadName, employer
)因此(academicID)
是Academic
的主键,而(paperNr, academicId)
是PaperInvolvement
表的主键。
这是我被要求做的触发器:
PaperInvolvement
,更新Academic
此表格中只有2个角色,Reviewer
和Author
这是我到目前为止所做的:
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
我的问题是,基于要求(我在子弹列表中列出的内容),这是回答问题的正确方法吗?
答案 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