thorv71
asked on
use select value as column name in sub sql
I need to use the value of a selected column as column name in sub sql.
Like this:
Select A.id, A.name, A.header, (Select A.name from table2 B where B.id = 2) as value from table1 A
A.name is the Clue here. that contains the column name that I need in the sub sql
How to do this ??
Like this:
Select A.id, A.name, A.header, (Select A.name from table2 B where B.id = 2) as value from table1 A
A.name is the Clue here. that contains the column name that I need in the sub sql
How to do this ??
Not 100% sure what you need, but this is my best guess:
Select A.id, A.name, A.header,
(Select B.id from table2 B where B.name = A.name) as value
from table1 A
Select A.id, A.name, A.header,
(Select B.id from table2 B where B.name = A.name) as value
from table1 A
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
No one of the other solution fixed my problem.
declare @fieldname nvarchar(max);
select @fieldname = A.name from table1 A
set @sql = 'Select A.id, A.name, A.header, (Select :FIELDNAME from table2 B where B.id = 2) as value from table1 A'
set @sql = REPLACE(@sql, ':FIELDNAME', @fieldname)
exec (@sql)