I have a "table A" with the following structure:
Act_Code ACT_TYPE_1 ACT_TYPE_2 ACT_TYPE_3 ACT_TYPE_4
-------- -------- ----------- ---------- -----------
ACT1 A NULL NULL NULL
ACT2 NULL B NULL NULL
ACT3 NULL NULL C NULL
ACT4 NULL NULL NULL D
ACT1 A NULL NULL NULL
As you can see, the ACT_TYPE data will always store into the field name which refers to the last digit of "Act_Code" fields: Eg. When Act_Code = "ACT1", the Act_Type is stored in field "ACT_TYPE_1" When Act_Code = "ACT2", the Act_Type is stored in field "ACT_TYPE_2" and so on...
Now, I want to read the data from the above "Table A" and insert into "Table B" which is having the following structure:
ACT ACT_TYPE
---- --------
1 A
2 B
3 C
4 D
Question: *1. How can I add "dynamic column name" inside a select query?*
For example,
INSERT INTO Table_B (ACT, ACT_TYPE)
SELECT RIGHT(Act_Code,1), ## FROM Table_A
How can I handle the dynamic column name as per the symbol "##" above?
I've tried:
SET @sql = 'INSERT INTO Table_B (ACT,ACT_TYPE) '
SET @sql = @sql + 'SELECT RIGHT(Act_Code,1), '
SET @sql = @sql + '''ACT_TYPE_'' + RIGHT(Act_Code,1) FROM Table_A'
EXEC (@sql)
But it doesn't work!
Please help, thanks very much!
CASEwithin a query to pick the value of the correct column.