I have a table that has an autoincrement surrogate key. I want to use it as a foreign key of my other table. The thing is, I cant figure out how I can reference it to that table, because it is nearly impossible to determine what I have to reference(the actual value of the surrogate key).
Please be noted that what I am trying to do is adding a tuple/record through my program(outside the dbms). The process is:
-
Add a new record in Table1 and generate an autoincrement key. Update
-
Add a new record in Table2 and reference its foreign key to the primary key of Table1. Update
My question is : HOW do I store the foreign key if I didnt know what is it?
Edit:
Sorry for not specifying the database and for the long reply. I use microsoft sql server.
If your DBMS supports sequences (which most modern DBMS do), simply generate the PK value for table1 then reference that FK value using the “currval” feature of your DBMS.
Something like (PostgreSQL syntax, but other DBMS supporting sequences have very similar functions):
Another option would be to simply get the ID value in your program and then use that value in both inserts.
If you have to deal with a DBMS that does not support sequences (e.g. MySQL or SQL Server before 2012) there is usually a function (e.g.
@@IDENTITYfor SQL Server) that lets you reference the generated ID value of table1 in the second INSERT statement (instead of the currval call)