简体   繁体   English

如何从SQL Server中的查询获取列名

[英]How to get column names from a query in SQL Server

Using SQL Server. 使用SQL Server。

I have a very extensive query, with a lot of aliasing, etc... 我有一个非常广泛的查询,带有很多别名,等等。

Is there a way, using just SQL (stored proc is fine, but not PHP, etc), to get a list of all column names from this query? 有没有一种方法,仅使用SQL(存储的proc很好,但是不使用PHP等)从此查询获取所有列名的列表? (I realize I will have to probably embed my query inside of this solution but that is fine. Just a temporary measure.) (我意识到我可能必须将查询嵌入此解决方案中,但这很好。这只是一个临时措施。)

Thanks! 谢谢!

If you're using SQL Server 2012 or later you can take advantage of sys.dm_exec_describe_first_result_set 如果您使用的是SQL Server 2012或更高版本,则可以利用sys.dm_exec_describe_first_result_set

SELECT name 
FROM 
sys.dm_exec_describe_first_result_set
('Your Query Here', NULL, 0) ;

DEMO 演示

This is too long for a comment. 这个评论太长了。

There are various ways that you can get the columns out of the query, such as: 您可以通过多种方式从查询中获取 ,例如:

select top 0 s.*
from (<your query here>) s;

Then you can parse the results. 然后,您可以解析结果。

However, I have found another approach useful. 但是,我发现另一种有用的方法。 Create either a view or a table using the same logic: 使用相同的逻辑创建视图或表:

select top 0 s.*
into _TempTableForColumns
from (<your query here>) s;

Then use information_schema (or the system tables if you prefer): 然后使用information_schema (或您喜欢的系统表):

select *
from information_schema.columns
where table_name = '_TempTableForColumns' and schema_name = 'dbo';

drop table _TempTableForColumns;

The advantage of this approach is that you can get type information along with the column names. 这种方法的优点是您可以获得类型信息以及列名。 But the engine still has to run the query and that might take time even though no rows are returned. 但是引擎仍然必须运行查询,即使没有返回任何行,也可能需要花费时间。 Although the column names and types are available after compiling, I am not aware of a way to get them without also executing the query. 尽管列名和类型在编译后可用,但我不知道在不执行查询的情况下获取列的方法。

After SQL Server 2008 在SQL Server 2008之后

select * 
from sys.columns c 
inner join sys.objects o on c.object_id = o.object_id 
where o.name = 'TableName'

Before 之前

select * 
from syscolumns c 
inner join sysobjects o on c.id = o.id 
where o.name = 'TableName'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM