Skip to content
Advertisement

How to loop through table using while loop and create another table with values needed

I have two tables: MainTable and MyTable. MyTable has unique ControlNo and ID. I need to add very first EffDate from MainTable to MyTablebased on ID and ControlNo.

enter image description here

For that I need to look at PreviousID column, then see if that PreviousID is in ID column and so on.

enter image description here

Desired output should look like this:

enter image description here


The below is an example with dummy data of getting proper EffDate by supplying an ID value. It works, but how can I loop through the whole MainTable, retrieve ID‘s and EffDate into separate table, then join that table to MyTable?

UPDATE: Adding dummy data tables

Advertisement

Answer

You can use a recursive query to traverse the hierarchy.

I would start by joining the original table with the main table, which restricts the paths to just the rows we are interested in. Then, you can recurse towards the parent. Finally, we need to filter on the top parent per path: top() and row_number() come handy for this.

Consider:

Demo on DB Fiddle:

controlno | id       | effdate   
--------: | :------- | :---------
     3333 | QuoteID3 | 2018-08-25
     7777 | QuoteID6 | 2019-02-10
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement