版本:SQL Server 2008 R2
此触发器检查主键违规(如果有)将行移动到历史记录表;然后删除该行;然后插入导致违规的行。
但它没有做好自己的工作。
CREATE TRIGGER [dbo].[ONINSERT]
ON [dbo].[TICKETS]
Instead of INSERT
AS
BEGIN
DECLARE @ID VARCHAR(200)
SET NOCOUNT ON;
SET @ID = (SELECT TICKET_ID FROM inserted)
INSERT TICKET_HISTORY
SELECT * FROM TICKETS
WHERE
TICKET_ID = @ID ;
print 'Inserting ' + @id
DELETE FROM TICKETS
WHERE TICKET_ID = @ID;
print 'Deleting' + @id
INSERT TICKETS
SELECT * FROM inserted;
print 'Inserting back' + @id
答案 0 :(得分:0)
即使您有多个插入内容,也只会触发一次,所以在您的情况下我不会发现这种情况......您不需要再次删除该行,因为而不是插入通常意味着&# 34;而不是插入执行一些自定义操作"
if exists
(
select 1 from inserted i
join
mytable t
on t.id=i.id
)
begin
--insert into tickets history
insert into ticketshistory
select i.* from inserted i
join
mytable t where t.id=i.id
---you can add custom logic to alert or simply ignore
return
end
--this is needed since if there is no violation you have to insert rows
insert into tickets
select * from inserted