返回字段名称作为SQL查询的一部分

时间:2016-10-20 12:20:56

标签: sql-server tsql

我需要编写一个Sql Satement,它会传递任何有效的SQL子查询,并返回结果集WITH HEADERS。

不知何故,我需要询问结果集,获取字段名并将它们作为“联盟”的一部分返回原始数据,然后将结果传递给导出。

在我的尝试之下:我有一个Sub-Query Callled“A”,它返回一个数据集,我需要查询它的字段名。 ?通常可能?

select A.fields[0].name, A.fields[1].name, A.fields[2].name  from 
(

Select 'xxx1' as [Complaint Mechanism]  , 'xxx2' as [Actual Achievements]
union ALL 
Select 'xxx3' as [Complaint Mechanism]  , 'xxx4' as [Actual Achievements]
union ALL 
Select 'xxx5' as [Complaint Mechanism]  , 'xxx6' as [Actual Achievements]   ) as A

任何指针都会受到赞赏(也许我只是错过了明显的......)

结果集应如下表所示:

F1                      F2
---------------------   ---------------------
[Complaint Mechanism]   [Actual Achievements]
xxx1                    xxx2
xxx3                    xxx4
xxx5                    xxx6

1 个答案:

答案 0 :(得分:1)

If you have a static number of columns, you can put your data into a temp table and then query tempdb.sys.columns to get the column names, which you can then union on top of your data. If you will have a dynamic number of columns, you will need to use dynamic SQL to build your pivot statement but I'll leave that up to you to figure out.

The one caveat here is that all data under your column names will need to be converted to strings:

select 1 a, 2 b
into #a;

select [1] as FirstColumn
        ,[2] as SecondColumn
from (
    select column_id
            ,name
    from tempdb.sys.columns
    where object_id = object_id('tempdb..#a')
    ) d
pivot (max(name)
        for column_id in([1],[2])
        ) pvt

union all

select cast(a as nvarchar(100))
    ,cast(b as nvarchar(100))
from #a;

Query Results:

| FirstColumn | SecondColumn |
|-------------|--------------|
|      a      |      b       |
|      1      |      2       |