的例子“使用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