I am trying to determine how to import some CSV data into a MS SQL database.
Unfortunatly it is not as simple as it sounds, since more then one table is involved. Also some of the fields will be pulled from the CSV, while others will have fixed values.
In terms of relating multiple tables, my logic would be as following:
IF <select count(course_name) from tbl_courses WHERE course_name = 'value from csv'> GT 0
THEN
ADD <data> to TBL_ITEM using PK from TBL_COURSES
ELSE
CREATE ROW in TBL_COURSES WITH <data>
ADD <data> to TBL_ITEM using PK from TBL_COURSES
END IF
Is there a way to map the fields in my CSV to the tbl_item (while adding a row to tbl_courses as needed?)
Basically you want to start thinking set based and carry out the following steps:
Import your CSV in to a temporary table.
Insert into your courses table selecting from your temp table, you can include your static data as well but make sure to distinct to ensure duplicate entries aren’t made.
Insert into your items table selecting from your temp table, including the course tables PK will depend on your CSV data. If you already have the unique course id as part of the CSV data then great, otherwise you can sub query as part of the insert.
Here’s an example of what I’m trying to explain if it helps, obviously courseData and itemData is really your set of fields…