This question has been asked before…but I can’t seem to find the exact answer I’m looking for… I need to insert a bunch of records and get back the inserted identity values… I’m doing this:
INSERT MyTable(col1, ....)
OUTPUT inserted.IdentityColumn
SELECT p.i.value('@XmlAttribute', 'nvarchar(128)') FROM @myXml.nodes('/root/i') AS p(i)
This works fine…
Enter SQL transactional replication with updatable subscriptions, which places triggers on replicated tables on subscribers.
OUTPUT no longer works in this scenario…
So, I’m doing this now…but I have a bad feeling in my gut about this and I think I’ve opened the door to a concurrency issue (though I’m not positive).
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
DECLARE @currentIdentity bigint
SET @currentIdentity = SELECT IDENT_CURRENT('MyTable') + 1
...
SELECT IdentityColumn FROM MyTable WHERE IdentityColumn <= IDENT_CURRENT('MyTable') AND IdentityColumn >= @currentIdentity
Suggestions? This also stinks because the approach doesn’t work for generated uniqueidentifiers.
You can use the variant of
OUTPUTthat inserts into a table variable. From the documentation:(Emphasis added)
So, you can have:
Which will have approximately the same behaviour as the original, unless you’re processing e.g. row count messages.