El ejemplo "Uso de un LMD DESPUÉS gatillo para hacer cumplir una regla de negocio entre los proveedores y PurchaseOrderHeader tablas" en la documentación de MSDN CREATE TRIGGER hace exaclty lo que estás buscando:
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;
La clave aquí es ROLLBACK TRANSACTION
, simplemente adapte el ejemplo para satisfacer sus necesidades y listo.
Editar: Esto debería lograr lo que está buscando, pero no lo he probado, por lo que su kilometraje puede variar.
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
Otra edición, basado en algunas suposiciones (Tenga en cuenta que escribí este guión sobre la marcha ya que no puedo probarlo ahora mismo):
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
)
De esta manera cuando se inserta registros en el dbo.results
tabla la restricción comprueba si el alumno aprobó el curso y cancela la inserción, si corresponde. Sin embargo, es mejor verificar esto en la capa de aplicación.
¿Qué DBMS estás usando? –