I am writing an Application that imports configuration data from multiple external systems. To decouple the user-data from imported data y am using an intermediate table. The following tables are simplified for the sake of the argument.
- table
[connection]
(generic connection information referenced by other tables not included) - table
[importConfig]
(Connection configuration from one of the external systems) - table
[connectionImportConfig]
(intermediate table, linking [connection] and [importConfig]
For each connection in [importConfig] I want to create a row in [connection] with an identity column. Then I want to insert the new IDs from [connection] together with the identifier from [importConfig] in [connectionImportConfig].
Constraint: I don't want to use a cursor. Must be a set-based solution.
The examples I have found on stackoverflow are either not set-based or I found them not applicable for other reasons.
T-SQL Insert into multiple linked tables using a condition and without using a cursor (not valid for multiple rows, using
@@IDENTITY
)How to perform INSERT/UPDATE to Linking (Join) table which has FKs to IDENTITY PKs (not valid for multiple rows. Not telling how to join the identity values with the original data I want to insert)
I have tried a lot and am stuck at the point where I have to insert the new IDs into connectionImportConfig
-- Test tables&data (stripped down version)
CREATE TABLE connection (ConnectionID int identity(1,1) NOT NULL, comment nvarchar(max) null)
CREATE TABLE connectionImportConfig(connectionID int NOT NULL, ConfigCode nvarchar(50) NOT NULL)
CREATE TABLE importConfig (ConfigCode nvarchar(50) NOT NULL)
DECLARE @MyConnection table (ConnectionID int not null);
insert into importConfig values ('a')
insert into importConfig values ('b')
insert into importConfig values ('c')
-- Insert into PK-table creating the IDs
INSERT INTO connection (comment)
OUTPUT INSERTED.ConnectionID INTO @MyConnection
SELECT * from importConfig
-- How do I insert the new IDs together with the ConfigCode? 1 has to be replaced with the ID.
-- JOIN doesn't seem to work because there is no join condition to use
INSERT INTO connectionImportConfig (connectionID, ConfigCode)
SELECT 1, ConfigCode FROM ImportConfig
select * from @MyConnection
select * from connectionImportConfig
-- Cleanup
DROP TABLE importConfig;
DROP TABLE connection;
DROP table connectionImportConfig;