Shakir
Shakir

Reputation: 273

Importing data from excel and inserting into normalized sql tables

I have an excel file with 815 records that includes service name and charge. In the database, some records have been entered so remaining 781 records need to inserted.

The problem is that there are 2 tables, one is departmentalservices and the other is deptservicedetails. Departmental service table has service name (among other things) and is joined to deptservicedetails by a column called service_id. Deptservicedetails is where the charge for that service will be present (as there are cash and credit charges but dont worry about that). Departmental services has all the service names but the charges for each of them is not present in the details table.

Now if I use the program normally to insert the charges, its gonna take long as you know. Hence, is there a way in which i can write multiple insert queries (using excel formula) or something that would match a name in the excel sheet with an id in the table and hence I can insert a record into the details table by id.

At the moment I could write an insert query with name and charge but the details table requires service id and not name with an insert query.

Hope its understood and thanks.

Upvotes: 0

Views: 2553

Answers (1)

markblandford
markblandford

Reputation: 3193

Without more detail this is all a bit of a shot in the dark.

In Excel you can simply write a formula to build your SQL INSERT statements and if you use INSERT INTO...SELECT statements you can get the service_id during the insert. An Excel formula something like this:

="INSERT INTO deptservicedetails SELECT " & B2 & "," & C2 & ", service_id FROM departmentalservices t2 WHERE t2.service_name = '" & A2 & "';"

Where cells B2 & C2 are values you want to insert (if they are strings then you'll need to include single quotes) and A2 contains the name of which you want to look up the ID for.

Of course you could also just export your name / id data to Excel, perform a VLOOKUP() and build your SQL that way.

I would first try this for one record, validate the SQL is correctly formed and then run it for all your inserts.

Upvotes: 2

Related Questions