I want to do after I an INSERT
in table X
to copy that record into another History
table immediately.
Now the table has the primary key as an Identity
column, so the record won't have an primary key id until it is actually inserted.
My question is开发者_JS百科 if I do a trigger
on this record will I get the identity id for that record or will it still be blank?
Yes the identity is available in the trigger but make sure you get that id correctly.
@@identity, SCOPE_IDENTITY etc are NOT what you want to do in a trigger!
SELECT @id = id FROM inserted
Is also a bad idea.
Always write your triggers to expect multiple changes being made simultaneously. The above approaches will all cause subtle but important errors when you insert more than one record into the table at a time.
The correct approach is to insert into your audit table FROM the inserted table
i.e.
INSERT INTO myAuditTable(Id, Datetime, user)
SELECT id, GETDATE(), USER_NAME())
FROM inserted
if you do the 'after insert' trigger, the record is already there with a value for the identity column.
Just make sure you declare the trigger as "AFTER" insert, not "FOR" or "INSTEAD OF" (guess you wouldn't use the last one... ;)
http://msdn.microsoft.com/en-us/library/ms189799.aspx
精彩评论