I’m working with a database table that has multiple similar columns and I need to transform the data into a normalized format.
Current table structure (TableX):
TableX
RecordID cost1 cost2 cost3 cost4 factor1 factor2 factor3 factor4
100 25 30 35 40 1.5 2.1 1.8 2.3
Target table structure (TableY):
RecordID Cost Factor
100 25 1.5
100 30 2.1
100 35 1.8
100 40 2.3
Currently I’m using a cursor to retrieve data:
Fetch next from my_cursor into @record_id, @cost1, @cost2, @cost3, @cost4, @factor1, @factor2, @factor3, @factor4
Then I need to insert the data with statements like:
insert into TableY (RecordID, Cost, Factor) values (@record_id, @cost1, @factor1)
The problem is I would need to write multiple insert statements for each column pair. Since I actually have about 30 similar columns in my real scenario, writing individual insert statements becomes impractical.
Is there an efficient way to iterate through these column pairs so I can use a single insert operation within a loop structure instead of writing 30 separate insert statements?