I use the INSTEAD OF insert trigger in the table to set the incremental version number in the row, and also copy the row to the second history / audit table.
Rows are inserted into both tables without problems.
However, I had problems returning a new identifier from the 1st table back to the user.
Scheme
CREATE TABLE Table1 ( id INT IDENTITY(1,1) PRIMARY KEY, name VARCHAR(250) NOT NULL UNIQUE, rowVersion INT NOT NULL ) CREATE TABLE Table1History ( id INT NOT NULL, name VARCHAR(250) NOT NULL, rowVersion INT NOT NULL ) CREATE TRIGGER TRG_INS_Table1 ON Table1 INSTEAD OF INSERT AS DECLARE @OutputTbl TABLE (id INT, name VARCHAR(250)) BEGIN
The connection in the name column in the insert trigger is not ideal, but it needs to handle multiple inserts at once.
e.g. INSERT INTO Table1 (name) VALUES('xxx'),('yyy')
Attempts to solve
When inserting SCOPE_IDENTITY is NULL .
INSERT INTO Table1(name) VALUES('xxx') SELECT SCOPE_IDENTITY() or INSERT INTO Table1(name) VALUES('xxx') RETURN SCOPE_IDENTITY()
I also tried using OUTPUT, which returns 0 :
DECLARE @IdentityOutput TABLE (id INT) INSERT INTO Table1(name) OUTPUT INSERTED.id INTO @IdentityOutput VALUES('xxx') SELECT id FROM @IdentityOutput
Lines are inserted with a penalty and have identifiers, but I cannot access them unless I use the following - which seems hacked:
INSERT INTO Table1(name) VALUES('xxx') SELECT id from Table1 WHERE name = 'xxx'
What is the right way to get a new ID
Decision
Can not be! You cannot reliably return an identifier when executing INSERT in a table with an INSTEAD OF trigger. The Sidux answer below is a good workaround for my situation (replace the INSTEAD OF trigger with the AFTER trigger and the DEFAULT columns have been added).