Sql 错误:锚点和递归部分之间的类型不匹配,十进制数据类型的递归cte
可能重复: 我有如下的东西Sql 错误:锚点和递归部分之间的类型不匹配,十进制数据类型的递归cte,sql,sql-server-2005,tsql,common-table-expression,Sql,Sql Server 2005,Tsql,Common Table Expression,可能重复: 我有如下的东西 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 f
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将返回不一定是小数6,2的类型,可以返回小数5,2。因此,它不能将这两个值合并在一起。这不应该被标记为一个副本,因为它处理十进制数据类型,而不是像所谓的副本那样的VARCHAR。这是一个很好的解释,我甚至认为这是一个错误,因为DBMS被告知只向CTE。看到一个中间结果将适合精度较低的小数,优化原始精度,然后抱怨降低的精度不够。如果我们决定有一天更改表,并允许更高的精度,甚至打破已经尝试和测试过的查询。遗憾的是,在当前版本的SQL Server 2019中,情况仍然如此。