简体   繁体   中英

select records from table given as column name. Dynamic sql

I've searched some topics here but there have not been any answers which I need. I want to make a query where I will join a table basing on the column name in the first table.

I'm using sql server so it would be appreciate if someone know solution for this technology.

Here is a sample what I wanna do:

Tables :

main_table
----------
id | tab      | another_col
----------------------
1 | product_x | abcd
2 | product_y | efgh


table_product_x
----------------------
id | yyy
----------------------
1 | simple_yyy_value1


table_product_y
----------------------
id | yyy
----------------------
2 | simple_yyy_value4

Output :

product_x | simple_yyy_value1 | abcd
product_y | simple_yyy_value4 | efgh

Query ( sketch )

select tab, yyy, another_col from main_table
join 'table_'+tab xxx on xxx.id = main_table.id

You can build this using union all and some dynamic SQL.

declare @SQL nvarchar(max)
declare @Pattern nvarchar(100)

set @Pattern = 'select ''[TABLE_NAME]'' as TableName, yyy from table_[TABLE_NAME]'

select @SQL = stuff((select ' union all '+replace(@Pattern, '[TABLE_NAME]', tab)
                     from main_table
                     for xml path(''), type).value('.', 'nvarchar(max)'), 1, 11, '')

exec (@SQL)

The statement executed will look something like this:

select 'product_x' as TableName, yyy 
from table_product_x 
union all 
select 'product_y' as TableName, yyy 
from table_product_y

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