选择所有列,并按其表和列命名

时间:2019-08-31 00:22:20

标签: sql sql-server

我有很多加入的声明。我想获取报表请求者的所有列,但我也想在表名中包含表名。我不想获取名为“ name”的列,而是要基于其表获取名为“ user.name”的列。我希望此过程能够自动完成而无需编写表名。

messageSource

1 个答案:

答案 0 :(得分:2)

您需要使用动态sql。首先使用information_schemastuff为您使用的表名及其对应的列名创建键值关系。

select column_name + '.' + table_name 
from information_schema.columns 
where table_name in ( 'table1', 'table2' ...)

之后,在最终输出查询中使用该值声明列名,但这也需要使用动态sql来完成,最后需要使用sp_executesp_executesql执行以获取最终值结果。

最终查询将是这样...

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

您可以根据自己的使用情况和条件更改查询中的某些部分。