可能重复:
CTE 错误:“锚点和递归部分之间的类型不匹配”
我有如下的东西
declare @t table (id int identity,Price decimal(6,2))
insert into @t
select 17.5 union all
select 10.34 union all
select 2.0 union all
select 34.5
现在,如果我编写如下查询
;with cte(id, price) as
(
select id, price
from @t
union all
select cte.id, cte.price + t.price
from cte
join @t t
on cte.id < t.id
)
select *
from @t
我在运行时收到以下错误:
锚点之间的类型不匹配 和递归部分....
我什至在类型转换(到十进制)后尝试了相同的操作,但结果相同......
但是,如果我类型转换为 int 它可以工作......但情况不应该是这样的(:
修复:
;with cte(id,price) as
(
Select id, price from @t
Union all
Select cte.id, cast(cte.price + t.price as decimal(6,2))
From cte
Join @t t
On cte.id < t.id
)
Select * from @t
说明:
表达式
cte.price + t.price
返回的类型不一定是decimal(6,2),可以返回decimal(5,2)。因此此后它无法合并这两个值。