You need to use dynamic sql. First create a key value relation of your used table name and its corresponding column name using information_schema
and stuff
.
select column_name + '.' + table_name
from information_schema.columns
where table_name in ( 'table1', 'table2' ...)
After that use this value in your final output query for declaring column names, but this is also need to be done using dynamic sql and finally need to execute using sp_execute
or sp_executesql
to get your final result.
Final query will be like this...
declare @col varchar(max)
set @col = Select stuff(
(select ', ' + column_name + '.' + table_name
from information_schema.columns
where table_name in ( 'table1', 'table2' ...) for xml
path('')),1,1,'')
declare @query nvarchar(max) = '
select ' + @col + '
from table1
inner join table2 on table1.id = table2.id '
exec sp_executesql @query
You can change some of the portion in the query as per your use and condition.