trigger for not inserting members doesnt work

情到浓时终转凉″ 提交于 2021-02-17 07:04:27

问题


I have this table

CREATE TABLE members
(
    member_id INT PRIMARY KEY NOT NULL,
    first_name VARCHAR(20),
    last_name VARCHAR(20),
    web_page VARCHAR(200),
    e_mail VARCHAR(200),
    cv VARCHAR(800),
    dep_id INT,
    teacher_id INT
);

and I want to create a trigger that if someone wants to insert a member which has a dep_id of 1 or 2 or 3.

And the teacher_id is different than NULL (as the teacher_id column is filled with either NULL or an id of another member)

I came up with this

CREATE TRIGGER employee_insup1 
ON members
FOR INSERT, UPDATE
AS
    DECLARE @dep_id INT, @teacher_id INT

    SELECT @dep_id = i.dep_id, @teacher_id = i.teacher_id
    FROM inserted i
  
    IF ((@dep_id = 1) AND (@teacher_id != NULL))
    BEGIN
        RAISERROR('Teacher_id expects NULL',16,1)
        ROLLBACK TRANSACTION
    END

but after all if I try to insert a member with dep_id 1 and teacher_id 7(for example) it will be registered


回答1:


You don't need a trigger for this. A check constraint is sufficient:

alter table members add constraint chk_members_dep_teacher
    check (dep_id not in (1, 2, 3) or teacher_id is not null);

Specifically, this ensures that when dep_id is in one of those departments, then the teacher_id is not null. You might find the logic easier to follow as:

alter table members add constraint chk_members_dep_teacher
    check (not (dep_id nt in (1, 2, 3) and teacher_id is null) );


来源:https://stackoverflow.com/questions/65430115/trigger-for-not-inserting-members-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!