I am migrating data between two databases. From the first database I am exporting a csv file that has the following columns:
Customer_Name
Contact_First_Name
Contact_Last_Name
Phone1
Phone2
Fax
I need to take this data and put it into the following tables for the new database:
Table: customer_contact
contact_id INT IDENTITY(1,1)
first_name VARCHAR(50)
last_name VARCHAR(50)
customer_id INT
PK = contact_id
Table: contact_phone
contact_id INT
phone_num VARCHAR(15)
in_use BIT
PK = contact_id, phone_num
Table: contact_fax
contact_id INT
fax_num VARCHAR(15)
in_use BIT
PK = contact_id, fax_num
My plan is to BULK INSERT
the data from the csv into a temporary table, and then use that to do INSERT
s into each of the other tables.
Since the main identifier for each contact if their first and last names, how do I insert the corresponding data into the phone and fax tables? I am using SQL Server.
Best Answer
This solution applies when you have repeated data in the CSV and you want to control what to do in every case. Since, there is nothing in your question about the following fields, I'm not including any logic for them:
0 - create the tables you already declared in your question
1 - create a t_Bulk table having the exact structure of your cvs and execute the bulk copy
2 - With the T_BULK table already full, let's process each record:
Good luck
In order to include an additional field:
in the declare zone include an aditional variable:
@Extension
.which you must include in both
FETCH NEXT
lines. Then you need to include that variable when inserting the phones, but in this case you need to check that phone2 is not equeal to phone1, just to ensure you don't have repeated phones: