我有以下SQL Server触发器,我想做以下事情:
- 在
INSERT
上,将Documents
中的新行保存到ArchivedDocuments
- 在
UPDATE
上,保存新行修订如果WordCount
或PageCount
或ContributorCount
已经改变了UPDATE
的当前值
我如何实现这一点?
我当前的触发器只是在INSERT
或UPDATE
之后保存到ArchivedDocument
。
编辑:Id
是文档表的主键。DocumentId
是引用Document.Id
的外键。
CREATE TRIGGER [TRG__Documents]
ON [Documents]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @now datetimeoffset = sysdatetimeoffset();
INSERT INTO [DocumentRevisions] ([DocumentId], [Time], [WordCount], [PageCount], [ContributorCount])
SELECT
[inserted].[Id],
@now,
[inserted].[WordCount],
[inserted].[PageCount],
[inserted].[ContributorCount]
FROM
[inserted]
END
您需要在deleted
表中EXCEPT
任何匹配的行。我假设Id
是主键,如果不是,那么您需要修改它以包含主键。
create trigger [TRG__Documents] on [Documents]
after insert, update
as
begin
set nocount on;
if(not exists (select 1 from inserted))
return;
declare @now datetimeoffset = sysdatetimeoffset();
insert into [dbo].[DocumentRevisions] (
[DocumentId],
[Time],
[WordCount],
[PageCount],
[ContributorCount]
)
select
i.[Id],
@now,
i.[WordCount],
i.[PageCount],
i.[ContributorCount]
from (
select
i.[Id],
i.[WordCount],
i.[PageCount],
i.[ContributorCount]
from inserted i
except
select
d.[Id],
d.[WordCount],
d.[PageCount],
d.[ContributorCount]
from deleted d
) i
end