Click here to Skip to main content
15,893,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have table1 and table2.
Primary key of table1 is auto updating recordID.
Foreign key of table2 is recordID of the table1.
What I'm currently doing is,
First insert to table1,
SQL
INSERT INTO table1(col1, col2, col3) VALUES (val1, val2 val3)

Then select the auto updated record id of the inserted record,
SQL
SELECT table1RecordID FROM table1 ORDER BY table1RecordID DESC LIMIT 1

And insert that record id to the table2 as the foreign key.
SQL
INSERT INTO table2(foreignKeyCol, col1, col2) VALUES (table1ReacordID, val1, val2)

Are there any other preferable ways of doing this?
Posted

1 solution

Don't do it like that! MySQL and MSSQL are multiuser systems, so there is no guarantee that your select will retrieve the ID of the record you just entered - there is nothing that stops a different user entering a record after you do, and before your select.
Instead, either use @@IDENTITY to retrieve the last automatically generated ID on teh current connection (you can use LAST_INSERT_ID()[^] as well, but @@IDENTITY works for MSSQL and MYSQL as well) or better, use GUID ID's and set them from your other code - that way you don't need to fetch anything once inserted.

SQL
INSERT INTO table1(col1, col2, col3) VALUES (val1, val2 val3)
INSERT INTO table2(foreignKeyCol, col1, col2) VALUES (@@IDENTITY, val1, val2)
 
Share this answer
 
Comments
Sherantha 4-Sep-15 3:57am    
Thank you very much. This is what I wanted. :)

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