Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output from INSERT INTO Stored Procedure

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);
like image 830
Abris Avatar asked Dec 16 '22 11:12

Abris


2 Answers

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 
like image 200
Nenad Zivkovic Avatar answered Dec 27 '22 15:12

Nenad Zivkovic


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 
like image 28
Devart Avatar answered Dec 27 '22 17:12

Devart