的例子「使用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
表約束檢查學生是否已通過課程,並在適當的情況下取消插入。但是,最好在應用程序層中檢查這些東西。
您正在使用哪些DBMS? – 2013-08-26 07:49:34