2011-06-09 69 views
2

Possible Duplicate:
CTE error: “Types don't match between the anchor and the recursive part”错误:类型不锚和递归部分,递归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 

我提示以下错误:在运行时:

Types don't match between the anchor and the recursive part....

我甚至试过同类型转换(十进制),但同样的结果后....

但是,如果我强制转换为int它的工作原理......但不应该是这样的(:

+1

这不应该被标记为重复,因为它处理的是Decimal数据类型,而不是像指称的重复那样处理varchar。 – JJS 2014-11-12 00:47:05

回答

2

的修复:

;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将返回不一定十进制(6,2)的类型,可以小数返回(5,2)。因此,它不能结合这两个值。