Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择所有列并按其表和列命名_Sql_Sql Server - Fatal编程技术网

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

Sql 选择所有列并按其表和列命名,sql,sql-server,Sql,Sql Server,我有一个包含很多连接的语句。我想获取报表请求者的所有列,但我还想在列的名称中包含表名。我不想获取名为“name”的列,而是希望基于其表获取名为“user.name”的列。我希望这个过程在不写表名的情况下自动完成 SELECT * AS TABLE_NAME.* FROM THOSE_TABLES 您需要使用动态sql。首先,使用information\u schema和stuff创建所用表名及其对应列名的键值关系 之后,在最终输出查询中使用此值来声明列名,但这也需要使用动态sql来完成,最

我有一个包含很多连接的语句。我想获取报表请求者的所有列,但我还想在列的名称中包含表名。我不想获取名为“name”的列,而是希望基于其表获取名为“user.name”的列。我希望这个过程在不写表名的情况下自动完成

SELECT * AS TABLE_NAME.* FROM THOSE_TABLES  

您需要使用动态sql。首先,使用information\u schema和stuff创建所用表名及其对应列名的键值关系

之后,在最终输出查询中使用此值来声明列名,但这也需要使用动态sql来完成,最后需要使用sp_execute或sp_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语句,这在AIK中是不可能的。可能与此相关:getting:Lookup Error-SQL Server数据库错误:关键字“Select”附近的语法不正确。这是第2行select。@syrkull:您可以共享一些示例表结构,在这些结构上您尝试应用内部联接并需要结果……或者您可以使用FIDLE来产生错误,这会更有帮助。
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