SQL row insert into a table + keys into its linking table within one statement (many-to-many relationship)
-
28-09-2019 - |
Question
Hey, I'm used to ORM so I have huge absence of sql experience. I want to know what is the best way to insert a row into a table, that is in many-to-many relationship with another table, and within the one statement also insert a row of two foreign keys into the particular linking table to preserve data integrity.
If anybody is using spring jdbcTemplate, I'd also want to know whether it has a support for this task. Thanks in advance
Solution
That's typically what stored procedures are used for, eg something like
CREATE PROC MyInsertM2M(@fieldname1 int, @fieldname2 varchar(20), @Key1 int, @Key2 int etc)
AS
BEGIN
INSERT INTO MyMainTable(fieldname1, fieldname2...)
VALUES(@fieldname1, @fieldname2...)
INSERT INTO MyResolverTable(KeyField1, Keyfield2)
VALUES (@Key1, Key2)
END
(assuming sql server)
Then google BEGIN TRAN, COMMIT TRAN and ROLLBACK.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow