SQL 服务器中 "With" 语句中的列名参数

Column name Arguments in the "With" Statement in SQL Server

微软在线文档(https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver15)中提到"With"语句可以将列名作为参数,然后说:

"The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition."

"if distinct names for all resulting columns are supplied in the query definition"究竟是什么意思?我经常使用 "With" 语句,但我从不在参数中指定列名。

我试图浏览整个文档,但似乎没有任何地方对此进行更详细的解释。

有谁知道什么情况下需要指定列名吗?

提前致谢!

很简单,定义 CTE 的查询的结果集必须 return 一组具有不同名称的列。例如,以下将不起作用:

with cte as (select 1 as x, 2 as x)
select * from cte; 

结果集有 2 列名为 "x"。在这种情况下,您必须在 cte 的定义中提供列名,因为查询会生成具有重复名称的结果集。因此,您需要使用以下形式:

with cte(x, y) as (select 1 as x, 2 as x)
select * from cte; 

一般来说,任何结果集的最佳做法是具有重复的列名。