I am trying to retrieve the latest identity value from an INSERT statement. Ignoring the question of which of OUTPUT, @@IDENTITY, or SCOPE_IDENTITY() is a better method, can I use OUTPUT to directly insert into an INT variable, or do I have to OUTPUT into table variable then select from that?
i.e. can I do something like (I know this does not work):
DECLARE @NewId INT
INSERT INTO MyTable (foo)
OUTPUT INSERTED.id INTO @NewID
VALUES ('bar');
Or do I always have to do:
DECLARE @NewId TABLE (NewId INT)
DECLARE @NewIdAsInt INT
INSERT INTO MyTable (foo)
OUTPUT INSERTED.id INTO @NewID
VALUES ('bar');
SET @NewIdAsInt = (SELECT TOP(1) NewId FROM @NewId)
OUTPUT INTO must refer to a table of some kind – a table variable, temporary or other table.
http://msdn.microsoft.com/en-us/library/ms177564.aspx
What is wrong with Scope_Identity() anyway?