Sql insert into mulitiple tables with new foreign key
Content provided by ChatGPT because I did not find this info online with my queries.
BEGIN TRANSACTION; -- Start a transaction
-- Insert data into the parent table
INSERT INTO ParentTable (column1, column2, ...)
VALUES (value1, value2, ...);
-- Get the auto-generated primary key value of the parent table
DECLARE @parentId INT;
SET @parentId = SCOPE_IDENTITY();
-- Insert data into the child table using the foreign key from the parent table
INSERT INTO ChildTable (column1, column2, parent_id)
VALUES (value1, value2, @parentId);
-- Insert data into another child table using the foreign key from the parent table
INSERT INTO AnotherChildTable (column1, column2, parent_id)
VALUES (value1, value2, @parentId);
COMMIT; -- Commit the transaction
- In MySQL 4.0+
- LAST_INSERT_ID()
- In SQL Server
- SCOPE_IDENTITY()
- In Sqlite
- last_insert_rowid()
also Sql setting variables .