2010-11-23 138 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