SQL Server How to pass one query respose as column of another query?

vngu2lb8  于 2023-06-21  发布在  其他
关注(0)|答案(3)|浏览(147)

I have to use SubClass1 as Column name of other query Like :

select SubClass1 from abc

how to pass Subclass1 as string in function

this is my Response of sql query

select Fieldname from xyz where id='1':

FieldName
----------------
SubClass1
gfttwv5a

gfttwv5a1#

You can use sub query, select sql command.

for example in your code:

SELECT SubClass1 as Column1,
       (SELECT Fieldname 
        FROM xyz 
        WHERE id='1') as Column2 
FROM abc

please use northwind simple database and try it... also return you respond about Nested select

lsmepo6l

lsmepo6l2#

You should use dynamic sql.

First store query response into a variable.

DECLARE @columnname varchar(50)=''
set @columnname=(select QUOTENAME(FieldName) from xyz where id=1)

then use that variable into dynamic sql query.

exec('select '+@columnname+' from abc')

NOTE: here example is only for single output from first query response. if you want multiple columns then you should use COALESCE to combine rows into a single result.

7xzttuei

7xzttuei3#

You can use dynamic SQL

DECLARE @variable varchar(max);
DECLARE @query varchar(max);
--Select the value you want to set as column name
SET @variable = (SELECT top(1) column_name FROM table1);
--Use the variable in the second table as column name
SET @query = 'select '+@variable+' from table2';
EXEC(@query);

相关问题