sql-server - 如何更新hierarchyid列
问题描述
我有一个名为的表items
,它有一个父/子关系,我将其转换为一个层次结构。
我已按照本教程这样做。
本教程的所有步骤都有效,除了最后的更新语句。
我收到错误消息:
不允许从数据类型 hierarchyid 到 nvarchar(max) 的隐式转换。使用 CONVERT 函数运行此查询。
但这没有任何意义。我正在更新的字段是一个hierarchyid,而不是一个nvarchar(nax)。所以我看不到哪里涉及到 nvarchar(max) 字段。
drop table #children
CREATE TABLE #Children
(
ID int,
TenantId int,
ParentID int,
Num int
);
GO
CREATE CLUSTERED INDEX tmpind ON #Children(TenantId, ParentID, ID);
GO
INSERT #Children (ID, TenantId,ParentID, Num)
SELECT ID, TenantId, ParentID,
ROW_NUMBER() OVER (PARTITION BY TenantId, ParentID ORDER BY ParentId)
FROM Items
GO
SELECT * FROM #Children ORDER BY TenantId, ParentID, Num
GO
WITH paths(path, ID, ParentId, TenantId)
AS (
-- This section provides the value for the root of the hierarchy
SELECT hierarchyid::GetRoot() AS OrgNode, ID, ParentId, TenantId
FROM #Children AS C
WHERE ParentId IS NULL
UNION ALL
-- This section provides values for all nodes except the root
SELECT
CAST(p.path.ToString() + CAST(C.Num AS varchar(30)) + '/' AS hierarchyid),
C.ID , C.ParentId, C.TenantId
FROM #Children AS C
JOIN paths AS p
ON C.ParentID = P.ID
)
-- This select statement runs just fine and shows expected data.
--Select i.Id as ItemId, p.path, p.path.ToString() as LogicalNode, p.Id, p.ParentId, p.TenantId from Paths P
--join Items I on p.Id = i.Id
--order by P.TenantId, P.path
--Note that I have tried using the convert function, but it still fails with the same error message.
UPDATE I Set OrgNode = Convert(hierarchyid, P.path)
FROM Items I
JOIN Paths AS P
ON I.ID = P.ID
GO
编辑 奇怪的是,这个DBFiddle有效。
解决方案
看起来 columnOrgNode
不是 type hierachyid
。你可以使用ToString()
UPDATE I Set OrgNode = P.path.ToString()
FROM Items I
JOIN Paths AS P
ON I.ID = P.ID
或更改表Items
并更改列类型。
推荐阅读
- javascript - 通过实时数据库 ServerValue 递增崩溃的云函数
- ruby-on-rails - Shopify API:退款未在 Shopify 中显示
- node.js - Node.js Discord 机器人的包文件错误
- python - 无法单击按钮硒
- firebase - Flutter firebase 在所有数据中添加一个类似的字段
- tensorflow2.0 - ImportError:无法从“tensorflow.python.eager.context”导入名称“VirtualDeviceConfiguration”
- javascript - WebStorm 无法识别 React JS 中的 HTML 标签
- node.js - Mongoose - 仅计数高于某个值
- php - 使用从 html 下拉列表中选择的 SQL 数据
- python - 开始使用 Google Analytics API 缺少软件包或软件包版本错误?