一個觸發器內三種INSERT,UPDATE,DELETE狀態
CREATE TRIGGER tr_T_A ON T_A for INSERT,UPDATE,DELETE
如IF exists (select * from inserted) and not exists (select * from deleted) 則為 INSERT
如IF exists(select * from inserted ) and exists (select * from deleted) 則為 UPDATE
如IF exists (select * from deleted) and not exists (select * from inserted)則為 DELETE
插入操作(Insert):Inserted表有數據,Deleted表無數據
刪除操作(Delete):Inserted表無數據,Deleted表有數據
更新操作(Update):Inserted表有數據(新數據),Deleted表有數據(舊數據)
筆者用到的案例:
create TRIGGER [risk].[Entry_Head_port_Exchange_Trigger]
ON [RiskH800].[risk].[ENTRY_HEAD]
AFTER INSERT,UPDATE
AS
DECLARE @COUNT INT
DECLARE @MANUAL_NO_COUNT INT
IF EXISTS (SELECT 1 FROM INSERTED)
IF EXISTS(SELECT 1 FROM DELETED)
BEGIN
SELECT @COUNT = COUNT(*) FROM risk.ENTRY_HEAD_port_EXCHANGE WHERE ENTRY_ID = (select ENTRY_ID FROM DELETED)
SELECT @MANUAL_NO_COUNT = COUNT(MANUAL_NO) FROM DELETED where substring(MANUAL_NO,1,1)= 'B' or substring(MANUAL_NO,1,1)='C'
IF @COUNT <=0 AND @MANUAL_NO_COUNT>0
INSERT INTO risk.ENTRY_HEAD_port_EXCHANGE(ENTRY_ID,CREATE_DATE)(SELECT ENTRY_ID,getdate() FROM DELETED)
END
ELSE
BEGIN
SELECT @COUNT = COUNT(*) FROM risk.ENTRY_HEAD_port_EXCHANGE WHERE ENTRY_ID = (select ENTRY_ID FROM INSERTED)
SELECT @MANUAL_NO_COUNT = COUNT(MANUAL_NO) FROM INSERTED where substring(MANUAL_NO,1,1)= 'B' or substring(MANUAL_NO,1,1)='C'
IF @COUNT <=0 AND @MANUAL_NO_COUNT>0
INSERT INTO risk.ENTRY_HEAD_port_EXCHANGE(ENTRY_ID,CREATE_DATE)(SELECT ENTRY_ID,getdate() FROM INSERTED)
END