In a join, how to prefix all column names with the table it came from

后端 未结 9 1780
你的背包
你的背包 2020-12-08 02:13

I\'m analysing a rather horrible legacy database/codebase, trying to reduce server load by combining queries into joins (including an email alert cron job that typically inv

9条回答
  •  不知归路
    2020-12-08 03:01

    You may try dynamic sql to create a query on the go as per the table definition.

    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
    
    

提交回复
热议问题