Output from INSERT INTO Stored Procedure - sql

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

Just try this after your insert statement and use this varible into second insert statement.:-
SET #BVar=SCOPE_IDENTITY()

You need to put the results of output into a table rather than just a scalar variable:
declare #tempId table (
id int
)
INSERT INTO AppInfo (name, logoUrl, userId)
OUTPUT inserted.id into #tempId
VALUES(#Name, #logoUrl, #userId);

Just use the following variable:
##IDENTITY

ALTER PROCEDURE [dbo].[addApp]
#Name varchar(50),
#logoUrl varchar(150),
#siteUrl varchar(150),
#userId int,
#canvasWidth int,
#canvasHeight int
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.AppInfo (name, logoUrl, userId)
OUTPUT inserted.id, #siteUrl, #canvasWidth, #canvasHeight
INTO dbo.CanvasApps(id, siteUrl, canvasWidth, canvasHeight)
SELECT #Name, #logonUrl, #userId;
END
GO

Related

Return inserted row from stored procedure

I have the following stored procedure
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
AS
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
SELECT #new_identity = SCOPE_IDENTITY()
SELECT * FROM NameAge where Id = #new_identity
Is there are a more efficient way to return the last inserted record complete with id and associated data?
Use Insertedwithin output clause,
As the follwoing:
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
AS
DECLARE #MyTableVar table(
Name varchar(50),
Identifier uniqueidentifier
;
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
OUTPUT INSERTED.Name, INSERTED.Identifier
INTO #MyTableVar
SELECt Name,Identifier from #MyTableVar
Refreance:
Best way to get identity of inserted row?
SCOPE_IDENTITY() is used to get the last generated Identity value in an identity column in your scope , For GUID values either you get the guid before you insert it like I have done in the code below , or you use OUTPUT clause to get the guid generated by the Insert statement.
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128)
AS
BEGIN
SET NOCOUNT ON;
Declare #NewID UNIQUEIDENTIFIER = NEWID();
insert into NameIdentifier ( Name, Identifier)
values( #name, #NewID);
SELECT * FROM NameAge where Id = #NewID;
END
This should give you your desired functionality.
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
#Ret int Output
AS
BEGIN
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
END
SET #Ret = ##IDENTITY
EDIT: This will return the id of your newly inserted row.
You can achieve this by using the output clause of SQL Server, you can read more about this here
if exists (select 1 from sys.tables where name = 'NameIdentifier ')
drop table NameIdentifier
create table NameIdentifier
(
id BIGINT IDENTITY(1,1)
,Name VARCHAR(100)
,Identifier uniqueidentifier
)
DECLARE #id TABLE
(
ID BIGINT
)
INSERT INTO NameIdentifier (Name,Identifier)
OUTPUT INSERTED.id INTO #id
VALUES('abcd',NEWID())
SELECT * FROM NameIdentifier N, #id I where N.id = I.id

SQL Server: How to use result from one INSERT for another INSERT

I have a stored procedure that is meant to update two tables at once.
My problem here is that the first table has an auto-incrementing ID column ("commentID") and my second table has a relationship on this so I need the newly created ID from the first INSERT in order to make the second INSERT.
I tried the following which I can save without errors but it doesnt execute as it should and does not update the tables as intended.
Can someone tell me what I am doing wrong here ?
My SQL:
ALTER PROCEDURE [dbo].[MOC_UpdateComment]
#imgID int,
#commentID int = '999999',
#comment nvarchar(1000),
#lastUpdate nvarchar(50),
#modBy varchar(50)
AS
BEGIN
DECLARE #temp AS TABLE
(
commentID int
)
SET NOCOUNT ON;
BEGIN TRANSACTION;
INSERT INTO MOC_BlogComments
(
imgID,
comment
)
OUTPUT inserted.commentID INTO #temp(commentID)
SELECT #imgID,
#comment
INSERT INTO MOC_LogComments
(
commentID,
lastUpdate,
modTime,
modBy
)
SELECT commentID,
#lastUpdate,
GETDATE(),
#modBy
FROM #temp
COMMIT TRANSACTION;
END
DECLARE #imgID INT,
#commentID INT = '999999',
#comment NVARCHAR(1000),
#lastUpdate NVARCHAR(50),
#modBy VARCHAR(50)
DECLARE #MORC_BlogComments AS TABLE
(
id INT IDENTITY(1, 1) NOT NULL,
imgid INT,
comment VARCHAR(100)
)
DECLARE #MORC_LogComments AS TABLE
(
commentid INT,
lastupdate DATETIME,
modtime DATETIME,
modby VARCHAR(100)
)
DECLARE #TEMP AS TABLE
(
commentid INT
)
SET nocount ON;
BEGIN TRANSACTION;
INSERT INTO #MORC_BlogComments
(imgid,
comment)
output inserted.id
INTO #TEMP(commentid)
VALUES (#imgID,
#comment)
INSERT INTO #MORC_LogComments
(commentid,
lastupdate,
modtime,
modby)
SELECT commentid,
#lastUpdate,
Getdate(),
#modBy
FROM #temp
SELECT *
FROM #MORC_LogComments
Function SCOPE_IDENTITY() returns the identity of last insert operation. You can use it to get the value which you need to use in second INSERT statement
You can use it like this in your statement:
INSERT INTO MORC_BlogComments (imgID, comment)
VALUES (#imgID, #comment)
INSERT INTO MORC_LogComments (commentID, lastUpdate, modTime, modBy)
VALUES (SCOPE_IDENTITY(), #lastUpdate, GETDATE(), #modBy)

SQL Server Stored Procedure - Return varchar id of inserted row

I'm working on a cascading insertion where a stored procedure should return an id of the inserted row. This would not be a problem if the id of the table was an int. However, the id is a varchar and therefore I cannot use SCOPE_IDENTITY().
This is my procedure so far:
CREATE PROCEDURE NEW_ARTICLE
#id varchar(50) OUTPUT,
#name varchar(100),
#articleNr varchar(50),
#gategory varchar(50),
#containerId varchar(50),
#contPerContainer int,
#pictureId varchar(50)
AS
SET NOCOUNT OFF
INSERT INTO nextlabel.[Article] (name, article_nr, category, container_id, count_per_container, picture_id )
VALUES (#name, #articleNr, #gategory, #containerId, #contPerContainer, #pictureId)
SET #id = SCOPE_IDENTITY()
Where the last row is not correct since the column id is a varchar.
How can I return the id?
Try this:
CREATE PROCEDURE NEW_ARTICLE
#id varchar(50) OUTPUT,
#name varchar(100),
#articleNr varchar(50),
#gategory varchar(50),
#containerId varchar(50),
#contPerContainer int,
#pictureId varchar(50)
AS
SET NOCOUNT OFF
SET #id = newid()
INSERT INTO nextlabel.[Article] (id, name, article_nr, category, container_id, count_per_container, picture_id)
VALUES (#id, #name, #articleNr, #gategory, #containerId, #contPerContainer, #pictureId)
GO

Pass Output Value of one stored procedure to another stored procedure

I want to use output value of one stored procedure in another stored procedure .
Stored procedure 1:
Create PROCEDURE [dbo].[usp_AddUpdateUser]
#UserId INT,
#Email varchar(50),
#FirstName varchar(50)
AS
BEGIN
MERGE [User] AS target
USING (SELECT #UserId) AS source (Id)
ON target.Id = source.Id
WHEN MATCHED THEN
UPDATE
SET Email = #Email,
FirstName = #FirstName
WHEN NOT MATCHED THEN
INSERT (Email, FirstName)
VALUES (#Email, #FirstName)
OUTPUT inserted.Id;
END
Now I want to use the inserted Id of above stored procedure to below stored procedure:
ALTER PROCEDURE usp_AddUpdateDealer
(#Id INT,
#DealerName varchar(55),
#Email varchar(55),
#UserId INT)
AS
BEGIN
DECLARE #NewUserId INT
EXEC #NewUserId = usp_AddUpdateUser #UserId, #Email, #DealerName
MERGE Dealer AS target
USING (SELECT #Id) AS source (Id) ON target.Id = source.Id
WHEN MATCHED THEN
UPDATE
SET #DealerName = #DealerName,
Email = #Email,
UserId = #NewUserId
WHEN NOT MATCHED THEN
INSERT (DealerName, Email, UserId)
VALUES (#DealerName, #Email, #NewUserId)
OUTPUT inserted.Id;
END
#NewUserId not gives the output value.
How can I got the output option of the usp_AddUpdateUser stored procedure to use that in next statement?
ALTER PROCEDURE usp_AddUpdateDealer
(
#Id INT,
#DealerName varchar(55),
#Email varchar(55),
#UserId INT
)
AS
BEGIN
DECLARE #t table(NewUserId INT )
INSERT #t(NewUserId)
EXEC #NewUserId = usp_AddUpdateUser #UserId,#Email,#DealerName
DECLARE #NewUserId INT
SELECT #NewUserId = NewUserId FROM #t
MERGE Dealer AS target
USING (SELECT #Id) AS source (Id)
ON target.Id = source.Id
WHEN MATCHED THEN
UPDATE
SET #DealerName = #DealerName,
Email = #Email,
UserId=#NewUserId
WHEN NOT MATCHED THEN
INSERT (DealerName,Email,UserId)
VALUES (#DealerName,#Email,#NewUserId)
OUTPUT inserted.Id;
END

How to have multiple inserts in one sql query that uses the identities from the previous table

I am trying to insert data into many tables in one SQL Server stored procedure. I am also using the identities from the tables that I have inserted data into to then resolve the many to many relationship by writing those identities to another table.
In theory the logic seems to be there for the stored procedure, but on execution only the first insert statement has been executed. Please could anyone assist with this.
The stored procedure is as follows:
Create Procedure [dbo].[InsertAllCustomerDetails]
(
--#CustomerID Bigint output,
#Firstname varchar(100),
#LastName varchar(100),
#Initials varchar(10),
#Title varchar(20),
#DateCreated datetime,
#isDeleted Bit,
--#ContactNumberID BIGINT Output,
#ContactNumber Varchar(100),
#ContactTypeID bigint,
#Street Varchar(550),
#AreaID BIGINT,
#isPreferred Bit
--#AddressID Bigint OutPut
)
AS
Insert Into Customer
(
FisrtName,
LastName,
Initials,
[Title],
DateCreated,
isDeleted
)
Values
(
#Firstname,
#LastName,
#Initials,
#Title,
#DateCreated,
#isDeleted
)
Declare #CustomerID BIGINT
SELECT #CustomerID = ##IDENTITY
RETURN #CustomerID
--This will now insert the contact details for the customer
Insert Into ContactNumber
(
ContactNumber,
ContactTypeID
)
Values
(
#ContactNumber,
#ContactTypeID
)
Declare #ContactNumberID BIGINT
SELECT #ContactNumberID = ##IDENTITY
--This will insert into the CustomerContactNumber
Insert Into CustomerContactNumber
(
ContactNumberID,
CustomerID
)
Values
(
#ContactNumberID,
#CustomerID
)
--This will insert the address
Insert Into [Address]
(
Street,
AreaID,
isPreferred
)
Values
(
#Street,
#AreaID,
#isPreferred
)
Declare #AddressID BIGINT
SELECT #AddressID = ##IDENTITY
--This will insert the relationship for the customer Address table
Insert into CustomerAddress
(
CustomerID,
AddressID
)
Values
(
#CustomerID,
#AddressID
)
I see two things:
You seem to have a typo in the Customer insert:
Insert Into Customer
(
FisrtName, <-- should be FirstName?
LastName,
You are RETURNing after the Customer insert - that's why only the first one runs
Declare #CustomerID BIGINT
SELECT #CustomerID = ##IDENTITY
RETURN #CustomerID <---- This exits the sproc
--This will now insert the contact details for the customer
Insert Into ContactNumber
I'm guessing the RETURN was there for debugging and not removed since it's obscured by the indentation.