如何检索选择查询的列标题?

时间:2015-09-12 09:56:08

标签: sql sql-server sql-server-2008-r2

如何在SQL Server中将选择查询的列标题检索为单个列? (最好检索列的数据类型)

查询示例:

select a.PartId, a.PartName, b.GroupName 
from Parts as a 
inner join Groups as b on a.GroupRef = b.GroupId

预期结果:

Columns 
--------
PartId
PartName
GroupName

3 个答案:

答案 0 :(得分:4)

SQL Server 2012+开始,您可以使用sys.dm_exec_describe_first_result_set获取有关结果集的所有元数据:

<强> DBFiddle Demo

DECLARE @tsql NVARCHAR(MAX) = 
  N'select a.PartId , a.PartName , b.GroupName 
from Parts as a inner join Groups as b 
on a.GroupRef = b.GroupId';

SELECT name AS [Columns]
FROM sys.dm_exec_describe_first_result_set(@tsql, NULL, 1)

答案 1 :(得分:2)

一种方法是使用结果集的模式创建临时表,然后查询tempdb的模式表以获取列名称和详细信息。您可以获得所有需要的详细信息。

    select a.PartId , a.PartName , b.GroupName into #yourtable
    from Parts as a inner join Groups as b 
    on a.GroupRef = b.GroupId
    where 1=2

    SELECT c.name as columnname,t.name as datatype
    FROM tempdb.sys.columns c
            inner join tempdb.sys.systypes as t on t.xtype = c.system_type_id
    WHERE [object_id] = OBJECT_ID(N'tempdb..#yourtable');

答案 2 :(得分:1)

    SELECT 'PartId', 'PartName', 'GroupName'
    UNION ALL
    select a.PartId , a.PartName , b.GroupName 
    from Parts as a inner join Groups as b 
    on a.GroupRef = b.GroupId