开发者

casting error using recursive CTE

开发者 https://www.devze.com 2023-02-08 14:38 出处:网络
I am trying to generate a list of numbers from -1 to 1 in .1 increments. The following is code is giving me an error:

I am trying to generate a list of numbers from -1 to 1 in .1 increments. The following is code is giving me an error:

WITH NumTab AS(
    SELECT -1.0 AS Num 
    UNION ALL 
    SELECT Num + .1
    FROM NumTab 
    WHERE Num <= 1.0
)
SELECT * 开发者_如何学GoFROM NumTab

Types don't match between the anchor and the recursive part in column "Num" of recursive query "NumTab".

I have tried casting all the numbers to decimal(2,1) with no change in results. There must be something obvious I am missing...


Cast both parts equally

WITH NumTab AS(
    SELECT cast(-1.0 as decimal(20,10)) AS Num 
    UNION ALL 
    SELECT cast(Num + .1 as decimal(20,10))
    FROM NumTab 
    WHERE Num <= 1.0
)
SELECT * FROM NumTab

Decimal(2,1) should work, but cast the full column, not the Num part only for the part after UNION

If you inspect the output after these statements:

SELECT -1.0 AS Num into dummytable
select Num + .1 as num2 into dummytable2 from dummytable
exec sp_columns dummytable
exec sp_columns dummytable2

Ouptut:

TABLE_NAME   COLUMN_NAME  TYPE_NAME  PRECISION  LENGTH  SCALE
dummytable   Num          numeric    2          4       1    
dummytable2  num2         numeric    3          5       1    

The literal -1.0 is implicitly cast to decimal(2,1). However, when you add another literal of .1 (which is implicitly decimal(1,1)), it has the potential to tip the decimal(2,1) data to a decimal(3,1), e.g. if 9.9 + 0.9 = 10.8, which is a decimal(3,1). So the types differ between the anchor and recursive portions.

0

精彩评论

暂无评论...
验证码 换一张
取 消