I maintain a PHP application with SQL Server backend. The DB structure is roughly this:
lot
===
lot_id (pk, identify)
lot_code
building
========
buildin_id (pk, identity)
lot_id (fk)
inspection
==========
inspection_id (pk, identify)
building_id (fk)
date
inspector
result
The database already has lots and buildings and I need to import some inspections. Key points are:
- It's a one-time initial load.
- Data comes in an Excel file.
- The Excel data is unaware of DB autogenerated IDs: inspections must be linked to buildings through their lot_code
What are my options to do such data load?
date inspector result lot_code
========== =========== ======== ========
31/12/2009 John Smith Pass 987654X
28/02/2010 Bill Jones Fail 123456B
Update: How I finally did it
In case someone else has to do a similar task, these are the steps the data load finally required:
Prepare the Excel file: remove unwanted columns, give proper names to sheets and column headers, etc.
With
SQL Server Import / Export Wizard
(32-bit version; the 64-bit version lacks this feature), load each sheet in the into a (new) database table. The wizard takes care of (most of) the dirty details, including creating the appropriate DB structure.Log into the database with your favourite client. To make SQL coding easier, I created some extra fields in the new tables.
Start a transaction.
BEGIN TRANSACTION;
Update the auxiliary columns in the newly created tables:
UPDATE excel_inspection$ SET building_id = bu.building_id FROM building bu INNER JOIN ....
Insert data in the destination tables:
INSERT INTO inspection (...) SELECT ... FROM excel_inspection$ WHERE ....
Review the results and commit the transaction if everything's fine:
COMMIT;
In my case, SQL Server complained about collation conflicts when joining the new tables with the existing ones. It was fixed by setting an appropriate collation in the new tables but the method differs: in SQL Server 2005 I could simply change collation from the SQL Server Manager (Click, Click, Save and Done) but in SQL Server 2008 I had to set collation manually in the import Wizard ("Edit SQL" button).