Friday, February 24, 2012

How to add (pick and choose) items from one table to another

We have two tables (one has DTS import of external spreadsheet - the other is the online table)

The scenario is that I need to add items (from the first table) to the second table, when they don't exist. However, it's harder than that - the second table, in some fields has integers (ID field)), referring to another table (let's call it the 3rd table), but the first table has text (which is in the description, in the third table).

I have to run through the first table, row by row, checking the part number if it already exists in the second table - nothing happens, and it goes to the next line. In each line, if the part number does NOT exist, I need to insert the data in that row. BUT - remember that third table, for the item(s) in the first table with text, I need to dynamically query the third table, to get the ID, in order to complete the insert correctly (Select ID from Third Table whereDescription=@.FirstTableFieldText)

I've never done anything like this, and I have no idea how to put this together - especially if it's all in one Stored Procedure. I need some help here on recommended ways to do it (and how).... Even the base structure (pseudo code- whatever) would help

I suppose that you can do it in one insert statement

Insert into SecondTable(partno,ID)

Select partno,thirdtable.ID from firsttable

LEFT JOIN thirdtable

ON thirdtable.description = firsttabledescription

where partno not in (select partno from secondtable)

I do not know exactly your database schema but in this TSQL statement you select records from first table and connect each record to its description ID ( join) and in where statement you select only records which has partno which does not exists in second table (destination).

Is it what you need?

Thanks

JPazgier

No comments:

Post a Comment