Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to make double insert

Tags:

sql

database

What's the best way of inserting information in table A and using the index from table A to relate to table B.

The "solution" I tried is inserting the info in table A (which has a automatically generated ID), then, select the last index and insert it in table B. This may not be very useful, as the last index may change between the inserts because another user could generate a new index in table A

I have had this problem with various DBMS postgreSQL, Informix, MySQL and MSSQL (thanks to lomaxx for the answer)

like image 944
seFausto Avatar asked Dec 06 '22 07:12

seFausto


1 Answers

if you're using MSSQL you could use SCOPE_IDENTITY to return the last id inserted in your current session. You can then use that to insert into table B.

This article from MSDN gives a decent example on how to do it.

like image 68
lomaxx Avatar answered Dec 28 '22 21:12

lomaxx