Solved

use select value as column name in sub sql

Posted on 2014-11-03
4
114 Views
Last Modified: 2014-12-06
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
Comment
Question by:thorv71
  • 2
4 Comments
 
LVL 11

Expert Comment

by:David Kroll
ID: 40420428
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
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 40420546
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
 

Accepted Solution

by:
thorv71 earned 0 total points
ID: 40473590
I had to solve this in another way, no one of the above solutions fixed my problem.
0
 

Author Closing Comment

by:thorv71
ID: 40484402
No one of the other solution fixed my problem.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

823 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question