Click here to Skip to main content
15,901,284 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a database with different tables, and I am currently writing to all of these tables. I am currently managing the ID of each table with a counter, but the thing is that I was told that each Id should auto increment and all the tables should be linked together with the id of the previous table.

What I have tried:

My table structure is this:
Activities: idactivity, idResult, Activity
Results: idResult, idObjective, Results
Objectives: idObjective, idProject
Projects: idProject, project

Iam able to write to all the tables, but I don't know how to link all the tables with the id from the previous table.
Posted
Updated 26-Jan-18 4:11am
Comments
Dileep CV 25-Jan-18 17:24pm    
If i am not wrong, your tables might have Primary key and Foreign key relationship with common field from previous table. Also you can do this using a stored procedure.

1 solution

Personally, I would use the built in
LAST_INSERT_ID()
function. [^] This will return the most recently inserted Id within the scope of the connection.

In doing so, you will need to get your hierarchy of table dependencies correct. From the look of it, the sequence of inserts should go like this:

SQL
Insert into Projects (your values)
SET @last_id_from_insert = LAST_INSERT_ID(); --which will return the Id for the new row you have inserted into the Projects table

Insert into Objectives (idProject)
Values (@last_id_from_insert)

SET @last_id_from_insert = LAST_INSERT_ID(); --update our variable to now be the Id of the row we have just inserted into the Objectives table

Insert into Results(idObjective)
Values (@last_id_from_insert)

SET @last_id_from_insert = LAST_INSERT_ID(); --update our variable to now be the Id of the row we have just insObjectives to the Results table

Insert into Activities(idResult)
Values (@last_id_from_insert)


As Dileep says, it would be good practice to do this within a stored procedure so that the connection scope is the same for each insert and retrieval of the latest Id.

Hope that helps.
 
Share this answer
 
v2

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