agn*_*tri 4 sql t-sql sql-server-2005 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
Run Code Online (Sandbox Code Playgroud)
现在,如果我编写如下查询
;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
Run Code Online (Sandbox Code Playgroud)
我在运行时收到以下错误:
锚点和递归部分之间的类型不匹配......
我什至在类型转换(到十进制)后尝试了相同的操作,但结果相同......
但是,如果我类型转换为 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
Run Code Online (Sandbox Code Playgroud)
解释:
表达式cte.price + t.price将返回的类型不一定是decimal(6,2),可以返回decimal(5,2)。因此此后它无法合并这两个值。
| 归档时间: |
|
| 查看次数: |
5356 次 |
| 最近记录: |