sql >> Database teknologi >  >> RDS >> Sqlserver

Sådan emulerer du en BEFORE DELETE-udløser i SQL Server 2005

Du kan bruge en I STEDET FOR trigger. Den udløses før (erstatter) den faktiske sletning, derfor skal den linkede post i [one_two] stadig eksistere.

create table [one] (one_id int not null primary key)
create table [two] (two_id int not null primary key)
create table [one_two] (one_id int, two_id int references two(two_id) on delete cascade)
GO
CREATE trigger t_del_two
on two
instead of delete
as
begin
SET NOCOUNT ON
DECLARE @Statement NVARCHAR(max)
SET @Statement = ''
SELECT @Statement = @Statement + N'EXEC [MyProc] ''' + CAST([one_two].[one_id] AS VARCHAR(36)) + '''; '
FROM deleted
JOIN [one_two] ON deleted.[two_id] = [one_two].[two_id]

PRINT (@Statement)
--EXEC (@Statement)

-- carry out the actual delete
DELETE TWO WHERE two_id in (SELECT two_id from deleted)
end
GO

Nogle eksempelværdier

insert into one select 1
insert into one select 2
insert into one select 3
insert into two select 11
insert into two select 12
insert into two select 13
insert into one_two select 1,11
insert into one_two select 1,13
insert into one_two select 2,13

Test det nu

delete two where two_id=13



  1. Hvordan tester man metoder, der beskæftiger sig med SQLite-database i Android?

  2. MySQL INSERT INTO / ON DUPLICATE KEY med SELECT-sætningsproblem

  3. Django og PostgreSQL - værdien er for lang til, at typetegn varierer (512)

  4. Er der en måde at vise en visning i et databasediagram i SQL Server 2008?