【问题标题】:SELECT ALL columns and name them by their table and column选择所有列并按它们的表和列命名
【发布时间】:2019-08-31 00:22:20
【问题描述】:

我有一个包含很多连接的语句。我想获取报告请求者的所有列,但我还想在列名中包含表名。我不想得到一个名为“name”的列,而是想根据它的表得到一个名为“user.name”的列。我希望这个过程可以自动完成,而不需要写表名。

SELECT * AS TABLE_NAME.* FROM THOSE_TABLES  

【问题讨论】:

标签: sql sql-server


【解决方案1】:

您需要使用动态 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

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

【讨论】:

  • 获取:查找错误 - SQL Server 数据库错误:关键字“选择”附近的语法不正确。这是第 2 行选择。
  • @syrkull:您能否分享一些您尝试应用内连接并需要结果的示例表结构......或者您可以制作小提琴以产生错误,这更有帮助。
猜你喜欢
  • 2023-04-04
  • 2015-01-06
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2016-07-18
相关资源
最近更新 更多