创建触发器阻止插入

时间:2010-11-23 11:51:12

标签: sql triggers

我正在尝试执行以下触发器:

create trigger t23 
on studies
after insert, update, delete 
as
begin
REFERENCING NEW ROW NewStudent
FOR EACH ROW
WHEN (30 <= (SELECT SUM(credits) FROM Studies)
DELETE FROM NewStudent N
WHERE N.spnr = NewStudent.spnr 
end

我正在尝试创建一个触发器,只有在学分为&lt;或==到'30'。 “Credits”是int类型。

我在尝试实现此触发器时遇到了很多错误。我真的尝试了一切,而且我没有选择。这个领域的专家可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:17)

CREATE TRIGGER MSDN文档中的“使用DML AFTER触发器强制执行PurchaseOrderHeader和Vendor表之间的业务规则”的示例确实可以满足您的需求:

USE AdventureWorks2008R2;
GO
IF OBJECT_ID ('Purchasing.LowCredit','TR') IS NOT NULL
   DROP TRIGGER Purchasing.LowCredit;
GO
-- This trigger prevents a row from being inserted in the Purchasing.PurchaseOrderHeader table
-- when the credit rating of the specified vendor is set to 5 (below average).

CREATE TRIGGER Purchasing.LowCredit ON Purchasing.PurchaseOrderHeader
AFTER INSERT
AS
DECLARE @creditrating tinyint, @vendorid int;
IF EXISTS (SELECT *
           FROM Purchasing.PurchaseOrderHeader p 
           JOIN inserted AS i 
           ON p.PurchaseOrderID = i.PurchaseOrderID 
           JOIN Purchasing.Vendor AS v 
           ON v.BusinessEntityID = p.VendorID
           WHERE v.CreditRating = 5
          )
BEGIN
RAISERROR ('This vendor''s credit rating is too low to accept new purchase orders.', 16, 1);
ROLLBACK TRANSACTION;
RETURN 
END;

此处的关键是ROLLBACK TRANSACTION,只需调整示例以满足您的需求即可。

编辑:这应该可以完成你想要的,但我没有测试过,所以你的里程可能会有所不同。

create trigger dbo.something after insert as
begin
    if exists ( select * from inserted where sum(credits) > 30 )
    begin
        rollback transaction
        raiserror ('some message', 16, 1)
    end
end

基于一些假设的另一个编辑(请注意我现在编写了这个脚本,因为我现在无法测试它):

create table dbo.students
(
    student_id int not null,
    name varchar (50) not null
)

create table dbo.courses
(
    course_id int not null,
    name varchar (50) not null,
    required_credits int not null
)

create table dbo.results
(
    student_id int not null,
    course_id int not null,
    course_result int not null
)

create trigger dbo.check_student_results on dbo.results after insert as
(
    declare @check int

    select @check = count(*)
    from inserted as a
    join dbo.courses as b on b.course_id = a.course_id
    where b.required_credits > a.course.result

    if @check <> 0
    begin

        rollback transaction

        raiserror('The student did not pass the course.', 16, 1)

    end
)

这样,当您在dbo.results表中插入记录时,约束会检查学生是否已通过课程,并在适当时取消插入。但是,最好在应用程序层中检查这些内容。