I'm writing a stored procedure where I first insert a new row in a table. The ID that is generated by this query is then needed for another query. Is it possible to access the prevoisly generated ID with the use of OUTPUT?
This is what I have done so far and it is pretty much a guess that didnt work
ALTER PROCEDURE [dbo].[addApp]
@Name varchar(50)
, @logoUrl varchar(150)
, @siteUrl varchar(150)
, @userId int
, @canvasWidth int
, @canvasHeight int
AS
DECLARE @tempId INT
SET @tempid = INSERT INTO AppInfo (name, logoUrl, userId)
OUTPUT inserted.id
VALUES(@Name, @logoUrl, @userId);
INSERT INTO CanvasApps (id, siteUrl, canvasWidth, canvasHeight)
OUTPUT inserted.id
VALUES(@tempid, @siteUrl, @logoUrl, @userId);
You can even do it in single statement:
ALTER PROCEDURE [dbo].[addApp]
@Name VARCHAR(50)
, @logoUrl VARCHAR(150)
, @siteUrl VARCHAR(150)
, @userId INT
, @canvasWidth INT
, @canvasHeight INT
AS BEGIN
INSERT INTO dbo.AppInfo (name, logoUrl, userId)
OUTPUT Inserted.ID, @siteUrl, @canvasWidth , @canvasHeight
INTO dbo.CanvasApps (id, siteUrl, canvasWidth, canvasHeight)
VALUES (@Name, @logoUrl, @userId)
END
Try this one -
ALTER PROCEDURE [dbo].[addApp]
@Name VARCHAR(50)
, @logoUrl VARCHAR(150)
, @siteUrl VARCHAR(150)
, @userId INT
, @canvasWidth INT
, @canvasHeight INT
AS BEGIN
DECLARE @tempId INT
INSERT INTO dbo.AppInfo (name, logoUrl, userId)
SELECT @Name, @logoUrl, @userId
SELECT @tempId = SCOPE_IDENTITY()
INSERT INTO dbo.CanvasApps (id, siteUrl, canvasWidth, canvasHeight)
SELECT @tempId, @siteUrl, @logoUrl, @userId
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With