2011-06-09 68 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)。因此,它不能結合這兩個值。