错误:锚点和递归部分之间的类型不匹配,十进制数据类型的递归cte

问题描述 投票:0回答:1

可能重复:
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 它可以工作......但情况不应该是这样的(:

sql sql-server-2005 tsql common-table-expression
1个回答
5
投票

修复:

;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)。因此此后它无法合并这两个值。

© www.soinside.com 2019 - 2024. All rights reserved.