I have a requirement to insert multiple rows into table1
and at the same time insert a row into table2
with a pkID
from table1
and a value that comes from a SP parameter.
I created a stored procedure that performs a batch insert with a table valued parameter which contains the rows to be inserted into table1
. But I have a problem with inserting the row into table2
with the corresponding Id (identity) from table1
, along with parameter value that I have passed.
Is there anyone who implemented this, or what is the good solution for this?
CREATE PROCEDURE [dbo].[oSP_TV_Insert]
@uID int
,@IsActive int
,@Type int -- i need to insert this in table 2
,@dTableGroup table1 READONLY -- this one is a table valued
AS
DECLARE @SQL varchar(2000)
DECLARE @table1Id int
BEGIN
INSERT INTO dbo.table1
(uID
,Name
,Contact
,Address
,City
,State
,Zip
,Phone
,Active)
SELECT
@uID
,Name
,Contact
,Address
,City
,State
,Zip
,Phone
,Active
,@G_Active
FROM @dTableGroup
--the above query will perform batch insert using the records from dTableGroup which is table valued
SET @table1ID = SCOPE_IDENTITY()
-- this below will perform inserting records to table2 with every Id inserted in table1.
Insert into table2(@table1ID , @type)