I created a trigger which creates a new row with a new ID after a change. When I use the trigger with one table it works but when I use it on a table which has reference to another table, I am getting an error:
DELETE statement conflicted with the REFERENCE constraint.
The tables look like this:
Table1:
ID BEZEICHNUNG MENGENEINHEIT PREIS .....
1 Harry Potter Book 20
2 iPod Music 150
Table2:
DIENSTLEISTUNG_ID RAUM_ID
1 2
2 1
Table 3:
ID Raumname ....
1 Elbe
2 Main
My trigger looks like this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[DIENSTLEISTUNG_Update]
ON [dbo].[DIENSTLEISTUNG]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @MAX_ID INT;
SELECT @MAX_ID=MAX(ID) FROM [DIENSTLEISTUNG];
declare @tmp Table(ID numeric, BEZEICHNUNG nvarchar(64), MENGENEINHEIT nvarchar(64),
PREIS numeric(19,5), BESCHREIBUNG nvarchar(64), VORLAUFZEIT numeric(10),
AZ_MO nvarchar(22), AZ_DI nvarchar(22),AZ_MI nvarchar(22),AZ_DO nvarchar(22),AZ_FR nvarchar(22),
AZ_SA nvarchar(22),AZ_SO nvarchar(22),DIENSTLEISTUNGSART_ID numeric(38),
UPDATE_USER numeric(38), UPDATE_DATE datetime, RUESTZEIT numeric(38),
PERMISSIONS numeric (38), KONTRAKTPOSITION numeric(38),ARTIKELNUMMER nvarchar(64),
ANZAHL numeric(10), BUCHUNGSHINWEIS nvarchar(255), SONDERWUNSCH char(1),
FLAG bit)
insert into @tmp
select
ID, BEZEICHNUNG, MENGENEINHEIT,
PREIS, BESCHREIBUNG, VORLAUFZEIT,
AZ_MO, AZ_DI,AZ_MI,AZ_DO,AZ_FR,
AZ_SA,AZ_SO,DIENSTLEISTUNGSART_ID,
UPDATE_USER, UPDATE_DATE, RUESTZEIT,
PERMISSIONS, KONTRAKTPOSITION,ARTIKELNUMMER,
ANZAHL, BUCHUNGSHINWEIS, SONDERWUNSCH,
1 [flag] from deleted;
delete T from DIENSTLEISTUNG T JOIN @tmp I
ON T.ID=I.ID
SET IDENTITY_INSERT [DIENSTLEISTUNG] ON
INSERT INTO [DIENSTLEISTUNG] (ID, BEZEICHNUNG, MENGENEINHEIT,
PREIS, BESCHREIBUNG, VORLAUFZEIT,
AZ_MO, AZ_DI,AZ_MI,AZ_DO,AZ_FR,
AZ_SA,AZ_SO,DIENSTLEISTUNGSART_ID,
UPDATE_USER, UPDATE_DATE, RUESTZEIT,
PERMISSIONS, KONTRAKTPOSITION,ARTIKELNUMMER,
ANZAHL, BUCHUNGSHINWEIS, SONDERWUNSCH,
FLAG)
SELECT @MAX_ID+ROW_NUMBER() OVER(ORDER BY ID) [ID],BEZEICHNUNG, MENGENEINHEIT,
PREIS, BESCHREIBUNG, VORLAUFZEIT,
AZ_MO, AZ_DI,AZ_MI,AZ_DO,AZ_FR,
AZ_SA,AZ_SO,DIENSTLEISTUNGSART_ID,
UPDATE_USER,GETDATE(),RUESTZEIT,
PERMISSIONS, KONTRAKTPOSITION,ARTIKELNUMMER,
ANZAHL, BUCHUNGSHINWEIS, SONDERWUNSCH,
0
FROM INSERTED
union all
select * from @tmp
SET IDENTITY_INSERT dbo.DIENSTLEISTUNG OFF
SET NOCOUNT OFF;
END;
The reason this is occurring is because although you are re-inserting a row with the same ID, at the time when you are deleting the row SQL has no way of knowing you are going to re-insert it to maintain the referential integrity.
It appears the purpose of this trigger is to not allow updates, and insert a new row whenever a change is made, so I think an
INSTEAD OFtrigger will be more suited to your needs. You can then just ignore any changes made to the existing row, and insert the new row, avoiding any deletions so avoiding any referencial integrity problems.