I am importing data from a flat file into a normalized table structure. I am currently using cursors to insert into linked tables, so I have primary keys to insert into the join table. Can I do this based on a set in SQL Server 2008 R2?
I have 3 tables: contacts, phones and contacts. After starting the import, I want there to be 2 contacts in the contact table, 2 in the phone table and 2 in the contactPhones table. Real imports are much more complicated, but this will allow me to transfer real imports from cursors to the installation solution.
It seems that the merge or output keywords should be able to do what I want, but I could not get the syntax to work.
Here is sample code trying to execute it using OUTPUT. I got this almost for work, except that I cannot reference import.contactId.
create table import(contactId int identity, phone varchar(50), name varchar(10)) create table contacts (contactId int identity, name varchar(50)) create table contactPhone (contactId int, phoneId int) create table Phones (phoneId int identity, number varchar(10)) go insert into import (phone, name) select '1872', 'dave' union (select '9110', 'Jordan') insert into contacts select name from import insert into Phones (number) OUTPUT import.contactId, INSERTED.phoneId into contactPhone select phone from import select * from contactPhone
Here is an example of code that is trying to merge:
create table import(contactId int identity, phone varchar(50), name varchar(10)) create table contacts (contactId int identity, name varchar(50)) create table contactPhone (contactId int, phoneId int) create table Phones (phoneId int identity, number varchar(10)) go insert into import (phone, name) select '1872', 'dave' union (select '9110', 'Jordan') insert into contacts select name from import MERGE phones target USING (select import.contactId, import.phone, import.name from import join contacts on import.contactId = contacts.contactId) as source ON (target.contactId = source.contactId) WHEN MATCHED THEN insert into Phones (number) OUTPUT import.contactId, INSERTED.phoneId into contactPhone select phone from import WHEN NOT MATCHED THEN INSERT (name) VALUES (source.Name) OUTPUT INSERTED.*; select * from contactPhone