错误 - 使用CTE进行递归选择时,"UNION运算符必须具有相同数量的表达式"

use*_*811 17 sql t-sql sql-server recursive-query

这时我有一张tblLocation带有柱子的桌子ID, Location, PartOfID.

该表以递归方式连接到自身: PartOfID -> ID

我的目标是选择输出如下:

> France > Paris > AnyCity >
Run Code Online (Sandbox Code Playgroud)

说明:AnyCity位于巴黎,巴黎位于法国.

我到现在为止找到的解决方案是这样的:

; with q as (
select ID,Location,PartOf_LOC_id from tblLocatie t
where t.ID = 1 -- 1 represents an example
union all
select t.Location + '>' from tblLocation t
inner join q parent on parent.ID = t.LOC_PartOf_ID
)
select * from q
Run Code Online (Sandbox Code Playgroud)

不幸的是我收到以下错误:

使用UNION,INTERSECT或EXCEPT运算符组合的所有查询在其目标列表中必须具有相同数量的表达式.

如果您知道如何修复我的输出,那就太棒了.

Yos*_*ari 20

问题在于:

--This result set has 3 columns
select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t
where t.LOC_id = 1 -- 1 represents an example

union all

--This result set has 1 columns   
select t.LOC_locatie + '>' from tblLocatie t
inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id
Run Code Online (Sandbox Code Playgroud)

为了使用unionunion all数量的列和它们的类型应该是相同的跨所有结果集.

我想你应该只将列添加LOC_deelVan_LOC_id到第二个结果集中