Solved

use select value as column name in sub sql

Posted on 2014-11-03
4
116 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

Suggested Solutions

Title # Comments Views Activity
Access join syntax when converting to T-SQL query 4 37
Location of Dynamics AX Service accounts in SQL 3 16
SQL R 21 29
Use column to search string column 2 12
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

821 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