简体   繁体   中英

Select columns name from subquery in main query

I have a question about select in SQL Server.

First I'm getting columns name from temp table with proper type query looks like this:

select 
    sc.name, st.name
from 
    tempdb.sys.columns sc
left join 
    sys.types st on sc.system_type_id = st.system_type_id
where 
    object_id = object_id('tempdb..#_tmpDocs')
    and st.name in ('char', 'varchar', 'nvarchar')

Result is a list of columns with type I want, but next I want to select those columns in different query so if ill save result from above query into temp table with name #columns with it be possible to do something like

 select (select * from #columns) from target_table

Here's a dynamic sql that will do what you need:

    CREATE TABLE #_tmpDocs (id INT, x CHAR(10), y VARCHAR(100))

    DECLARE @cols NVARCHAR(1000)
    DECLARE @sql  NVARCHAR(1000)

    SELECT  @cols = COALESCE(@cols + ',', '') + QUOTENAME(SC.name)
    FROM    tempdb.sys.columns sc
            LEFT JOIN sys.types st ON sc.system_type_id = st.system_type_id
    WHERE   object_id = OBJECT_ID('tempdb..#_tmpDocs')
            AND st.name IN ( 'char', 'varchar', 'nvarchar' )

    SET @sql = 'select ' + @cols + ' from #_tmpDocs'

    PRINT @sql

    EXEC (@sql)

    EXEC sp_executesql @sql

Chose between EXEC (@sql) and EXEC sp_executesql @sql based on you needs - see here to get an idea of what each is doing.

I don't think you can reference columns dynamically in SQL like that. Just doing a pure sql version, it won't work:

declare @x varchar(50) = 'MyColumn';
select @x from dbo.MyTable

You'll need to use dynamic sql , and build a string:

declare @x nvarchar(50) = 'MyColumn';
declare @y nvarchar(250) = 'select ' + @x + ' from dbo.MyTable';

EXECUTE sp_executesql @y

So in your case you may want to loop through your return result or otherwise turn it into a string of column names that can be concatenated to a larger query (like above).

Did you try this?

SELECT *
FROM   tempdb.sys.columns
WHERE  object_id = object_id('tempdb..#columns');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM