现在我有一个包含student_id和section_id的courseenroll表的表,以及一个具有不同section_id和限制学生数的section表。和学生表有不同的student_id。
我是触发器的初学者。现在我需要触发约束。例如学生从网络用户界面jsp一个接一个地插入,如果学生人数大于本节中学生的数量,我应该向用户显示错误信息。 “要显示的错误消息应包括来自数据库服务器的错误文本,可能还附有您自己的消息,该消息明确标识了违反的约束。”
我尝试按照此链接中的示例SQL using trigger for constraint 修改如下:
CREATE TRIGGER enroll_out_of_limit on courseenroll
AFTER INSERT, UPDATE
AS
IF EXISTS (
SELECT *
FROM section AS T
INNER JOIN (
SELECT section_id, COUNT(*) AS limitstu
FROM courseenroll
GROUP
BY section_id
) AS E
ON T.section_id = E.section_id
AND E.limitstu > T.limitstu
)
BEGIN
RAISERROR ('A teachers''s student tally is too high to accept new students.', 16, 1);
ROLLBACK TRANSACTION;
RETURN
END;
虽然它在“on”周围的代码开头给我错误,所以如何解决这个问题? 感谢
节表有两个属性:section_id和limitstudent
学生表有一个属性:student_id
courseenroll有两个属性:student_id和section_id
只要课程表中某一部分的学生人数不超过相应的限制,本节的学生就可以了。
我按照教程进行操作 我有以下触发器,但它在select语句
周围给出了错误 CREATE OR REPLACE FUNCTION enroll_out_of_limit()
RETURNS trigger AS
$BODY$
begin
if (SELECT *
FROM section AS T
INNER JOIN (
SELECT section_id, COUNT(*) AS limitstu
FROM courseenroll
GROUP BY section_id
) AS E
ON T.section_id = E.section_id
AND E.limitstu > T.limitstu ) THEN
RAISE EXCEPTION 'this section enrolllist is full!';
end if;
end;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION enroll_out_of_limit()
OWNER TO postgres;
如果我更改下面的sql,它可以创建触发器但是当我尝试插入时,它给出了“查询没有目标”的错误
create or replace function enroll_out_of_limit()
returns trigger as
$BODY$
begin
SELECT T.limitstu, E.currentsum
FROM section AS T
INNER JOIN (
SELECT section_id, COUNT(*) AS currentsum
FROM courseenroll
GROUP BY section_id
) AS E
ON T.section_id = E.section_id ;
if E.currentsum = T.limitstu
THEN
RAISE EXCEPTION 'this section enrolllist is full!';
end if;
end;
$BODY$
LANGUAGE 'plpgsql';
CREATE TRIGGER enroll_out_of_limit
before INSERT ON courseenroll for each ROW
EXECUTE PROCEDURE enroll_out_of_limit();