My SQL Server table:
[dbo].[Rep] ( [rep_ID] INT IDENTITY (300, 1) NOT NULL, [Restaurant_ID] INT NULL, [Fname] VARCHAR (50) NOT NULL, [Lname] VARCHAR (50) NOT NULL, CONSTRAINT [PK_Rep_ID] PRIMARY KEY CLUSTERED ([rep_ID] ASC), CONSTRAINT [FK_Restaurant_ID] FOREIGN KEY ([Restaurant_ID]) REFERENCES [dbo].[Restaurants] ([ID]) );
I want to create a stored procedure that return the auto generated key for the inserted record.
My current stored procedure:
CREATE PROCEDURE [dbo].[createRepAcc] @first varchar(50), @last varchar(50) AS INSERT INTO Rep([Fname], [Lname]) OUTPUT inserted.rep_ID VALUES (@first, @last); It's able to insert into the table but only return 1 instead of the primary key generated.
What am I doing wrong?
INSERTit'll pass back the value ofrep_IDfor the row inserted in a dataset.Restaurant_IDand that column does not allow NULL. Probably in an attempt to simplify the code you posted, you have obfuscated the actual cause of the problem.Restaurant_IDfor be NULLable, your SP works fine: DB<>Fiddle. Either we're missing pieces of the puzzle, or...?EXEC @Variable = {Stored Procedure};syntax? If so, that might explain why. An SP returns the value0for a success and a non-zero value to indicate failure (which this would based on the information we have). Perhaps the failure is therefore causing the return value to be1. If you want to pass the value back of the inserted ID to a variable you should be usingOUTPUTparameters.