2010-11-23 108 views
8

我试图执行以下触发:创建触发器防止插入

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 

我试图创建一个触发器,它只有在学分<或==为“30”插入一个学生。 “积分”是一个int类型。

我收到很多错误,试图实现此触发器。我真的已经尝试了一切,我没有选择。有人在这个领域的专家指出我在正确的方向?

+1

您正在使用哪些DBMS? – 2013-08-26 07:49:34

回答

12

的例子“使用DML AFTER触发器执行PurchaseOrderHeader和供应商表之间的业务规则”的CREATE TRIGGER MSDN文档中确实exaclty你在找什么:

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表约束检查学生是否已通过课程,并在适当的情况下取消插入。但是,最好在应用程序层中检查这些东西。

+1

+1提到“......最好在应用程序层检查这些东西。” – BigM 2014-10-16 08:10:43