Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a stored procedure with two insert statements where id/primary_key from the first insert statement will be used in second?

I see that there is a very similiar question already answered that discusses this same issue, but i just cannot seem to understand it. Below is a copy of my code that is in a stored procedure. I need to somehow, have the second insert statement insert the CompanyID generated from the first, into this second Statement. I appreciate any help i can get.

Thank You!!

@comp_name nvarchar (50),
@City nvarchar (50),
@State nvarchar (10),
@Address ntext,
@Zip_Code nvarchar (50),
@Country nvarchar (50),
@cust_name nvarchar (50),
@CompanyID int
AS
INSERT INTO Company_Listing
(comp_name, City, State, Address, Zip_Code, Country)
VALUES (@comp_name, @City, @State, @Address, @Zip_Code, @Country)

INSERT INTO Customer_Listing
(cust_name, City, State, Address, Zip_Code, Country, CompanyID)
VALUES (@comp_name,@City,@State,@Address,@Zip_Code,@Country,@CompanyID)
like image 385
John Avatar asked Dec 16 '22 09:12

John


1 Answers

Assuming this is for SQL Server - Yes, use SCOPE_IDENTITY:

@comp_name nvarchar (50),
@City nvarchar (50),
@State nvarchar (10),
@Address ntext,
@Zip_Code nvarchar (50),
@Country nvarchar (50),
@cust_name nvarchar (50),
@CompanyID int
AS
INSERT INTO Company_Listing
(comp_name, City, State, Address, Zip_Code, Country)
VALUES (@comp_name, @City, @State, @Address, @Zip_Code, @Country)

INSERT INTO Customer_Listing
(cust_name, City, State, Address, Zip_Code, Country, CompanyId)
VALUES (@comp_name,@City,@State,@Address,@Zip_Code,@Country,SCOPE_IDENTITY())

From MSDN's documentation on SCOPE_IDENTITY():

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

like image 159
Abe Miessler Avatar answered May 02 '23 03:05

Abe Miessler