我正在尝试找到一种将记录插入表的方法,该表使用新生成的 Identity 值作为其层次结构 ID 的一部分。以下 sql 演示了我正在尝试做的事情,以及我设法做到的最接近的事情。这是在事务内部使用插入后跟更新。我在想出初始层次结构 id 时遇到了麻烦,因为该字段有一个唯一的约束,我担心如果同时将 2 个元素添加到同一个父级,可能会引发错误。
DECLARE @hierarchy_elements TABLE (
id int IDENTITY (1, 1) NOT NULL ,
element_path hierarchyid NOT NULL
)
-- Cheating here, but I need some data to append to.
INSERT INTO @hierarchy_elements(element_path)
SELECT ('/1/')
UNION ALL SELECT ('/1/2/')
-- See that we have a couple elements in the table.
SELECT id, element_path.ToString() as [path] from @hierarchy_elements
-- arbitrarily pick a parent to append to
DECLARE @parentElementId int = 2
-- grab that parent's path.
DECLARE @parentElementPath hierarchyid
SELECT @parentElementPath = element_path FROM @hierarchy_elements WHERE id = @parentElementId
-- This is what I want to do. Use the current id as the last part of the hierarchyid
INSERT INTO @hierarchy_elements (element_path)
VALUES(@parentElementPath.ToString() + CAST(scope_identity() AS VARCHAR(20)) + '/')
-- This works, but kind of sucks.
BEGIN TRANSACTION
-- Insert under the parent with a known invalid id.
INSERT INTO @hierarchy_elements (element_path)
VALUES(@parentElementPath.ToString() + '-1/')
-- now update setting the last element in the hierarchyid to the id just generated.
UPDATE @hierarchy_elements
SET element_path = @parentElementPath.ToString() + CAST(SCOPE_IDENTITY() AS VARCHAR(20)) + '/'
WHERE id = SCOPE_IDENTITY()
COMMIT TRANSACTION
-- See that id 3 would fail the unique constraint check, but id 4 is correct.
SELECT id, element_path.ToString() as [path] from @hierarchy_elements
如果可能的话,我想使用单个语句插入,该语句将在 hierarchyid 字段中包含新的 Identity 值。