nosbor
nosbor

Reputation: 2999

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

Upvotes: 1

Views: 2281

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

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

Upvotes: 1

Related Questions