我用于审计的这个 AFTER INSERT 触发器有问题:
无法将值 NULL 插入到列“TermID”、表“AuditTerms”中;列不允许空值。插入失败。
TermKeys 表定义:
TermID int Identity PK
Key int
Action int
AuditTerms 表定义:
TermID int PK
UpdatedAt datetime
触发器定义:
ALTER TRIGGER [dbo].[TRG_TermKeys_AuditTerms_IUD] ON [dbo].[TermKeys]
AFTER INSERT, UPDATE, DELETE NOT FOR REPLICATION AS
BEGIN
SET NOCOUNT ON;
DECLARE @termid int;
IF EXISTS(SELECT * FROM Deleted) SELECT @termid = TermID FROM Deleted;
IF EXISTS(SELECT * FROM Inserted) SELECT @termid = TermID FROM Inserted;
IF EXISTS(SELECT TermID FROM AuditTerms WHERE (TermID = @termid))
BEGIN
UPDATE AuditTerms SET UpdatedAt = getdate() WHERE (TermID = @termid);
END
ELSE
BEGIN
INSERT INTO AuditTerms (TermID, UpdatedAt) VALUES (@termid, getdate());
END;
END;
TermID 是一个 Identity 字段和 PK,此时 Inserted 表是否包含 Identity 值?
我应该使用@@Identity 还是其他方式?