Working in SQL Server 2005, I have a stored procedure that inserts a record and returns the new ID via SELECT @@IDENTITY; as the last command.
I then want to call this from another stored proc, and get the value of the new ID.
But I can't work out how to get the value returned from the first procedure.
Example:
CREATE PROCEDURE spMyInsert(@Field1 VARCHAR(10)) AS
BEGIN
INSERT INTO tMyTable (Column1) VALUES (@Field1); // ID column implicitly set
SELECT @@IDENTITY ID;
END
CREATE PROCEDURE spMyMain AS
BEGIN
DECLARE @NewID INT;
EXEC spMyInsert 'TEST';
// How do I set @NewID to the value returned from spMyInsert?
END
There is another question that nearly answers my question, but not quite. This explains how to insert the results into another table, but all I want to do is store it in a local variable.
Looking at other similar questions, the general answer is to change to either set an OUTPUT variable or create a function to do it, but I can't do this in my case as other .NET data access stuff uses the same stored proc, and I don't want to have to duplicate all the work of the stored procs as functions as well.
I couple of things that I've tried but all fail are:
SET @NewID = (EXEC spMyInsert 'TEST');
SET @NewID = (SELECT ID FROM (EXEC spMyInsert 'TEST'));
Anybody know how to do this?
Thanks, Ben