[英]Column names of a CTE in SQL Server
I know it is possible to SELECT , from sys.columns and from tempdb.sys.columns the names of the columns of a specific table. 我知道可以从sys.columns和tempdb.sys.columns中 选择特定表的列的名称。
Can the same be done from a CTE ? 可以从CTE完成同样的事情吗?
with SampleCTE as (
Select
'Tom' as Name
,'Bombadill' as Surname
,99999 as Age
,'Withywindle' as Address
)
is there any way to know that the columns of this CTE are Name,Surname,Age and Address , without resorting to dumping the CTE result to a temporary table and reading the columns from there? 有没有办法知道这个CTE的列是Name,Surname,Age和Address ,而不是将CTE结果转储到临时表并从那里读取列?
Thanks! 谢谢!
Here is a "dynamic" approach without actually using Dynamic SQL. 这是一种“动态”方法,但实际上并没有使用动态SQL。
Unpivot (dynamic or not) would be more performant Unpivot(动态与否)会更高效
Example 例
with SampleCTE as (
Select
'Tom' as Name
,'Bombadill' as Surname
,99999 as Age
,'Withywindle' as Address
)
Select C.*
From SampleCTE A
Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
Cross Apply (
Select Item = a.value('local-name(.)','varchar(100)')
,Value = a.value('.','varchar(max)')
From B.XMLData.nodes('/row') as C1(n)
Cross Apply C1.n.nodes('./@*') as C2(a)
Where a.value('local-name(.)','varchar(100)') not in ('ID','ExcludeOtherCol')
) C
Returns 返回
Item Value
Name Tom
Surname Bombadill
Age 99999
Address Withywindle
Yes, it is possible sys.dm_exec_describe_first_result_set : 是的,可能是sys.dm_exec_describe_first_result_set :
This dynamic management function takes a Transact-SQL statement as a parameter and describes the metadata of the first result set for the statement. 此动态管理功能将Transact-SQL语句作为参数,并描述该语句的第一个结果集的元数据。
SELECT name
FROM sys.dm_exec_describe_first_result_set(
N'
with SampleCTE as (
Select
''Tom'' as Name
,''Bombadill'' as Surname
,99999 as Age
,''Withywindle'' as Address
)
SELECT * FROM SampleCTE
', NULL, NULL);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.