Constraint Vrs Triggers
En el siguiente ejercicio compararemos como funciona una restricción check contra un trigger de tipo after  los dos cumpliendo la misma función, validando que no se permita ingresar menores de 18 años, en una tabla que llamaremos «Estudiante».
Tengamos en cuenta que el trigger es reactivo es decir se ejecuta después que el dato es insertado, eliminado o modificado segun sea el tipo de trigger, mientras que la
restricción (constraint) es proactivo es ejecutado antes de insertar, modificar o eliminar el dato.
restricción (constraint) es proactivo es ejecutado antes de insertar, modificar o eliminar el dato.
| 
 –Agregar el campo a la tabla 
alter table estudiantes 
add fechanacimiento date 
–Poner una restriccion que solo permita mayores de edad 
alter table estudiantes 
add constraint Ck_fecha check  
(Datediff(Year,fechanacimiento,getdate()) >=18) 
select * from estudiantes 
–Probar la restruccion con una diferentes fechas 
UPDATE ESTUDIANTES SET fechanacimiento=’01-01-1975′ 
WHERE ID_Estudiante=1 
go 
UPDATE ESTUDIANTES SET fechanacimiento=’01-01-2014′ 
WHERE ID_Estudiante=1 
go 
–Borrar la restriccion para hacer lo mismo pero con un trigger 
alter table estudiantes 
drop constraint Ck_fecha 
go 
/*Crear el trigger, como es posible que se ingresen varias filas 
al mismo tiempo creamos un cursor y revisaremos dato por dato 
insertado y de no cumplir lo eliminaremos*/ 
CREATE TRIGGER COMPROBAR_FECHA 
ON ESTUDIANTES FOR INSERT 
AS 
BEGIN 
DECLARE @ID_Estudiante varchar(20) 
DECLARE @FechaNac varchar(255) 
DECLARE TableCursor CURSOR FOR 
SELECT ID_Estudiante, FechaNacimiento FROM ESTUDIANTES 
OPEN TableCursor 
FETCH NEXT FROM TableCursor INTO @ID_Estudiante, @FechaNac 
WHILE @@FETCH_STATUS = 0 
BEGIN 
if Datediff(Year,@FechaNac,getdate()) <=18  
     Delete Estudiantes where id_estudiante=@ID_Estudiante 
FETCH NEXT FROM TableCursor INTO @ID_Estudiante, @FechaNac 
END 
CLOSE TableCursor 
DEALLOCATE TableCursor 
END 
–Probar el trigger insertando varios datos al mismo tiempo 
Insert into estudiantes( nombre, fechanacimiento) 
values (‘Juan Perez’,’01-01-1970′),(‘Luis Perez’,’01-01-2014′), 
(‘Ana Perez’,’01-01-1970′) 
 | 
