Link to home
Start Free TrialLog in
Avatar of mbs2000
mbs2000

asked on

Using a TSQL cursor to import data

I have written an export routine in TSQL which imports data from a flat file database into a new database which contains different tables but links all the fields to the main data table.

Having been able to successfully import one data record and all of its linked fields (USING SELECT AND INSERT INTO statements, I need to automate the process using a cursor and import thousands of records. I would like to achieve the following:

Import from a select statement all of the main table data, which I believe would be loaded into the cursor. This holds the foreign key for linking the other tables

I then want to pass the record IDs from the above results and somehow link this with the next batch of inserts in the cursor so that all of the data is linked to the correct tables when running the cursor?

How would I go about this in TSQL?
Avatar of derekkromm
derekkromm
Flag of United States of America image

If you're able to link between the 2 tables, then a cursor may not be necessary.

First, you can do your insert into the main table.

Then, join your second table to the new main table based on the FK relationship. This will get you the ID information you require for the insert statement. Then you should have the necessary information to run the insert.
ASKER CERTIFIED SOLUTION
Avatar of derekkromm
derekkromm
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial