Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have two tables.. I want to insert records in tables by transaction using stored procedure.
there is primary and foreign key relationship between tables.. product_id is field of one table. it is primary key and auto incremented. so how I insert product_id in second table which is foreign key of table..
So plz help me..
thanks in advance..
Posted
Updated 9-Nov-14 21:59pm
v2
Comments
Shweta N Mishra 10-Nov-14 3:55am    
Did you tried to insert the data in both table in same transaction ?
Thanks7872 10-Nov-14 3:57am    
Have you tried :

insert into first_table.....
insert into second_table....?
heta.dave 10-Nov-14 4:03am    
Thanks for your valuable time..
I didn't get product_id for second_table.. it is auto identity in first table.So how to get product_id for second_table..
Maciej Los 10-Nov-14 4:05am    
Your question is not clear. Please provide more details about your requirements.
heta.dave 10-Nov-14 4:11am    
table name: Products
Cols: ProductID, ProductName, ProductDescription

table: ProductImages:
cols: ProductImageID, ProductID, ProductImageName

product table has productid which is auto incremented n also primary key.. It is auto incremented in table.. but how get that value of productID in productImages table

Insert first into the table having primary key
and then insert in second table having foreign key.
 
Share this answer
 
Let's imagine this scenario:
1) add record to Main table ad get primary key value
SQL
CREATE PROCEDURE InsertToMain
    @<value_list>
AS
BEGIN 
    INSERT INTO MainTable(<field_list>)
    VAULES(<value_list>)

    RETURN @@IDENTITY
END

2) when you added value to Main table, you're able to add values to child table

For further information, please see:
@@IDENTITY (Transact-SQL)[^]
Walkthrough: Using Only Stored Procedures (C#)[^]
How to: Execute a Stored Procedure that Returns a Single Value[^]
Try. Good luck!
 
Share this answer
 
SQL
CREATE PROCEDURE InsertData
@Param1	int,     --Main Table
@Param2	varchar(10),--Main Table
@Param3	varchar(300),--Child Table
@Param4	char(4)--Child Table
AS
BEGIN
	DECLARE @pkMain int

	INSERT INTO MainTable (Col1, col2)
		VALUES (@Param1, @Param2);

	SELECT
		@pkMain = SCOPE_IDENTITY();

	INSERT INTO ChildTable (col1, col2, col3)
		VALUES (@pkMain, @Param3, @Param4);

END
 
Share this answer
 
Comments
heta.dave 10-Nov-14 5:17am    
It works..
thanks a lot..
Arora_Ankit 10-Nov-14 5:18am    
you are welcome:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900