Link to home
Start Free TrialLog in
Avatar of thorv71
thorv71Flag for Norway

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 ??
Avatar of David Kroll
David Kroll
Flag of United States of America image

declare @sql nvarchar(max);
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)
Avatar of Scott Pletcher
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
ASKER CERTIFIED SOLUTION
Avatar of thorv71
thorv71
Flag of Norway image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of thorv71

ASKER

No one of the other solution fixed my problem.