Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all

I am working with .net and Mysql as database.
Please help me on below query which i am finding from last 2 days.

I have 2 tables

First table: Table1
Auto_ID | FirstName | Address | Status | Table2_ID

Second table: Table2
Auto_ID | Table1_ID | Action_Item | Cur_Status


I have to insert multiple records in Table1 where Table1 and Table2 are interlinked like a single record in Table1 can have multiple entry in Table2.

It is one to many relationship.

And as soon as record is entered in Table2 it auto_id should be updated in Table 1 > within column Table2_ID

I have created below triggers
First trigger to insert record in Table2 when record in entered in Table1
create trigger tr1
AFTER INSERT ON Table1
for each row
begin
Set @Action=new.Action;
Set @Ref_id=new.Auto_id;
Insert into Table2 (Table1_ID, Action_Item, Cur_Status)
Values((Select @Ref_id),'Value1','Value2');
End

Second trigger to update auto_id in Table1 when record in inserted in Table2 through trigger.
CREATE Trigger tr2
AFTER INSERT ON Table2
For each row
Begin
set @Auto_id=new.Auto_id;
set @Cur_Status=new.Cur_Status;
update Table1
set
Table2_ID
= (select @Auto_id), Status =(select @Cur_Status)
where
auto_id=@Ref_No;

End


But after insert records in first table getting below error:
Can't update table ‘Table1’ in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

Please note: My only intention is to insert multiple data in both the table at the same time and maintain the auto_id of second table in first table

Any help is greatly appreciated.
Posted
Comments
King Fisher 30-Jan-14 8:22am    
you can do one by one

1 solution

GO
/****** Object: StoredProcedure [dbo].[Sp_CourseAndBatchInsert] Script Date: 01/31/2014 12:16:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE proc [dbo].[Sp_inserttable1andtable2data]
(@Auto_ID as int =null,
@FirstName as varchar(50)=null,
@Address as varchar(50)=null,
@Status as varchar(50)=null,
@Action_Item as varchar(50)=null,
@Cur_Status as varchar(50)=null
)
as

declare @getAuto_ID int;

BEGIN
INSERT INTO table1(FirstName,Address) VALUES (@FirstName,@Address)

set @getAuto_ID=(Select @@IDENTITY)
END
BEGIN
INSERT INTO table2(Action_Item,Cur_Status,Auto_ID) VALUES (Action_Item,@Cur_Status,@getAuto_ID)
END

GO

try this
 
Share this answer
 
Comments
Sushma_Patel 31-Jan-14 4:27am    
Thanks for reply.
Above will work for single entry. What if i want to insert multiple records like 10 in table1 and 10 in table2, Yes, i can do it with for loop but i want to elimiate it.

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