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)
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.
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