Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 167
  • Last Modified:

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 ??
0
thorv71
Asked:
thorv71
  • 2
1 Solution
 
David KrollCommented:
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)
0
 
Scott PletcherSenior DBACommented:
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
0
 
thorv71Author Commented:
I had to solve this in another way, no one of the above solutions fixed my problem.
0
 
thorv71Author Commented:
No one of the other solution fixed my problem.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now