I am beginner user and have some basic knowledge of the SQL. I have to write a query to select the records from a table and insert into another table. My TABLE1 has almost 180+ columns and TABLE2 has only 6 columns. In TABLE2 first 4 columns are static and will be coming directly from TABLE1. Other 2 columns in TABLE2 are dynamic. They will be populated by each of 180+ columns with column name and column value from TABLE1. Let me explain this using structure if it is not very clear:
>T1:
>===
>Col1, Col2, Col3, Col4, Col5,..........,Col175, Col176, Col177, Col178, Col179, Col180
>
>T2:
>===
>Col1, Col2, Col3, Col4, NewCol1, NewCol2
So I want a query to select records from T1 and insert them into T2 such that
T2.Col1 = T1.Col1
T2.Col2 = T1.Col2
T2.Col3 = T1.Col3
T2.Col4 = T1.Col4
T2.NewCol1 = Column_Name from T1 (i.e. Col5, Col6, Col7... Col180)
T2.NewCol2 = Column_Value of the column which we are storing in T2.NewCol2
Here are sample:
T1:
Col1 | Col2 | Col3 | Col4 | Col5 | Col6 | Col7 | Col8 | Col9 | Col10 | Col11 | Col12
Val1 | Val2 | Val3 | Val4 | Val5 | Val6 | Val7 | Val8 | Val9 | Val10 | Val11 | Val12
T2:
Col1 | Col2 | Col3 | Col4 | Col5 | Col6
Val1 | Val2 | Val3 | Val4 | Col5 | Val5
Val1 | Val2 | Val3 | Val4 | Col6 | Val6
Val1 | Val2 | Val3 | Val4 | Col7 | Val7
Val1 | Val2 | Val3 | Val4 | Col8 | Val8
Val1 | Val2 | Val3 | Val4 | Col9 | Val9
.
.
Val1 | Val2 | Val3 | Val4 | Col12 | Val12
I want to achieve this in a single dynamic query. Apologies for the formatting and if anything is not clear. Please let me know if you need anything.
Thanks,
Sanjay