Skip to content
Advertisement

Insert into two tables and affect the id of one of the table columns into the other table

I have a Folder table which contain the following columns:

And I have another one called Images which contains:

I want to insert an url in the folder table in a query and put it in the images and get the id in the same query.

Actually, I am working on an Android project, I have to add a new folder and upload an image to it so that’s why I need this.

Is there a way to do it?

Advertisement

Answer

You’ll want to use SCOPE_IDENTITY() to capture the key value being generated by the IMAGE table. Some people use @@IDENTITY, do not do that, it has a global scope and you can sometimes get back the wrong ID.

Then use that value to insert into the FOLDER table. It feels a little backwards to insert into the IMAGE table first but that’s how you get the ID you want. Here is a fully functional example:

Results:

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement