Probablemente no desee un activador INSTEAD OF
a menos que desee reemplazar la inserción o actualización real. En su caso, desea un activador FOR INSERT, UPDATE
en su lugar.
Este disparador de ejemplo imprime un mensaje al cliente cuando alguien intenta agregar o cambiar datos en la tabla de títulos.
USE pubs
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'reminder' AND type = 'TR')
DROP TRIGGER reminder
GO
CREATE TRIGGER reminder
ON titles
FOR INSERT, UPDATE
AS RAISERROR ('inserts and updates to the titles table is not allowed', 16, 1)
GO
También se puede usar cosas como IF EXISTS
COLUMNS_UPDATED
o así.
Aquí hay otro ejemplo que usa la reversión.
USE pubs
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'employee_insupd' AND type = 'TR')
DROP TRIGGER employee_insupd
GO
CREATE TRIGGER employee_insupd
ON employee
FOR INSERT, UPDATE
AS
/* Get the range of level for this job type from the jobs table. */
DECLARE @min_lvl tinyint,
@max_lvl tinyint,
@emp_lvl tinyint,
@job_id smallint
SELECT @min_lvl = min_lvl,
@max_lvl = max_lvl,
@emp_lvl = i.job_lvl,
@job_id = i.job_id
FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id
JOIN jobs j ON j.job_id = i.job_id
IF (@job_id = 1) and (@emp_lvl <> 10)
BEGIN
RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)
ROLLBACK TRANSACTION
END
ELSE
IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl)
BEGIN
RAISERROR ('The level for job_id:%d should be between %d and %d.',
16, 1, @job_id, @min_lvl, @max_lvl)
ROLLBACK TRANSACTION
END
no estoy seguro de si tiene una transacción o no, pero en su caso, usted podría querer algo como lo siguiente:
USE myDatabase
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'myTable' AND type = 'TR')
DROP TRIGGER tr_myTrigger
GO
CREATE TRIGGER tr_myTrigger
ON myTable
FOR INSERT, UPDATE
AS
if(exists(select * from inserted where rtrim(c) <> ''))
begin
-- check to make sure the insert(s) are unique
if(exists(
select * from inserted i
join dbo.myTable t on i.a = t.a and i.b = t.b and i.c = t.c)
begin
raiserror('Duplicate(s) found', 16, 1)
rollback transaction
end
end
¿Cuál es la naturaleza de la "comprobación previa"? Los disparadores tienen una sobrecarga que maneja las tablas 'inserted' /' deleted'. ¿Es algo que puede aplicarse de otra manera? –
Todo lo que necesitamos es una restricción única sobre triples (3 columnas) ignorando cadenas vacías en una columna. – Cartesius00
Entonces, para tuple '(a, b, c)' si 'c' tiene un valor de cadena vacía, ¿quiere ignorar por completo esa tupla a los efectos de la restricción única? –