我创建了一个运行良好的 SQL Server 层次结构。
但是,我在需要十进制加法的层次结构级别数据类型处理中遇到问题。
我试过下面的这个查询可以添加小数并完美地工作。
SELECT
CAST('4.1' AS DEC(3,1)) + CAST('0.1' AS DEC(3,1)) ; --correct result: 4.02
但是,在我的 CTE 层次结构查询中,我收到了如下所示的错误。我认为错误是一致的:
CAST(parent.[OWNER LEVEL] AS DEC(3,1)) + CAST(0.1 AS DEC(3,1)) AS [OWNER LEVEL],
错误:
SQL 错误 [240] [S0001]:递归查询“CTE1”的“OWNER LEVEL”列中的锚点和递归部分之间的类型不匹配。
代码:
WITH CTE1 AS
(
SELECT
CAST('4.1' AS DEC(3,1)) as [OWNER LEVEL],
[OWNER ID],
[OWNER NAME],
CAST('4.2' AS DEC(3,1)) as [OWNED LEVEL],
[OWNED ID],
[OWNED NAME]
FROM
OWNER_OWNED
UNION ALL
SELECT
CAST(parent.[OWNER LEVEL] AS DEC(3,1)) + CAST(0.1 AS DEC(3,1)) AS [OWNER LEVEL],
child.[OWNER ID],
child.[OWNER NAME],
CAST(parent.[OWNED LEVEL] AS DEC(3,1)) + CAST(0.1 AS DEC(3,1)) AS [OWNED LEVEL],
child.[OWNED ID],
child.[OWNED NAME]
FROM
OWNER_OWNED child
INNER JOIN
CTE1 parent ON parent.[OWNED ID] = child.[OWNER ID]
)
SELECT * FROM CTE1