Skip to content
Advertisement

Match column name with data from other table

I have dynamically created a temp table #temp1 that create column dynamically based on a json string. The table will look like as below

#temp1

ID Field FRUIT VEGE
1 Field1 A B
2 Field2 C D

I would like to fill in the value column only in result table based on the #temp1 table, the field and type_id is already filled beforehand

result table

ID field type_id value
1 Field1 1 A
2 Field1 2 B
3 Field2 1 C
4 Field2 2 D

where the type_id can get from another table that specified the type and its id

type table

ID type_id type
1 1 FRUIT
2 2 VEGE

The type table will have many different types in it, I just list out the only two that is used in this question only.

Please help!

my attempt query:

Advertisement

Answer

You will need to use Dynamic Query as your column is dynamic

note : char(13) is new line. It helps to do simple formatting of the query

db<>fiddle demo

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement