简体   繁体   中英

Get column names of dynamic temp table to use in table join select

Anyone have an example of joining a temp table where the columns could be dynamic to another query where the query is selecting specific columns? I understand the join but the issue is that the select would have to do a sub query (I'm guessing?) on the column names and that can't be hardcoded in since the columns could change in the future with some being deleted or added.

A basic example is:

select table1.Name as Name,
    table1.Truck as Truck,
    table1.Address as Address,
    table1.City as City,
    (select * from #temp)
from table1
    left outer join #temp
        on #temp.asset_no = table1.asset_no

I know it can work if it is something like:

select *
from table1
    left outer join #temp
        on #temp.asset_no = table1.asset_no

or it will work if I get specific with the column names but I can't know the column names for sure of the dynamic table.

Do I need to loop through them somehow or do a sub query in the select statement?

Thanks in advance!

I ended up getting this figured out.

Here is the simplified code:

select table1.Name as Name,
table1.Truck as Truck,
table1.Address as Address,
table1.City as City,
table2.*
from table1
left join (
    select *
    from temp
) table2 on table2.asset_no = table1.asset_no

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