I'm creating a stored procedure that adds a tree, inserts nodes into that tree and then updates the nodes to include the parent id. I'm updating the nodes to include the parent id, because the parent nodes are inserted at the same time as the child nodes so they don't have an id yet.
My issue is that I'm unable to create a query that will set the codes of the parent id in the column of the correct child nodes. I have tried JOIN
, UNION
, INTERSECT
and subqueries, but I haven't been able to get it to work.
Update statement:
UPDATE [dbo].[Node]
SET ParentId = dn.Code
FROM [dbo].[Node] as dn
???
The @nodes
variable is a table that contains the following:
node_code | parent_code |
---|---|
'001' | null |
'002' | null |
'003' | '001' |
'004' | '003' |
Existing data in Node Table, before trying to update ParentId:
id | Code | ParentId |
---|---|---|
00000000-0000-0000-0000-000000000001 | '001' | null |
00000000-0000-0000-0000-000000000002 | '002' | null |
00000000-0000-0000-0000-000000000003 | '003' | null |
00000000-0000-0000-0000-000000000004 | '004' | null |
The Node table is created like this (simplified because mine contains more columns):
CREATE TABLE [dbo].[Node]
(
[Id] UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWSEQUENTIALID(),
[Code] VARCHAR(MAX),
[ParentId] UNIQUEIDNETIFIER FOREIGN KEY REFERENCES [Node](Id),
[TreeId] UNIQUEIDENTIFIER FOREIGN KEY REFERENCES [Tree](Id)
)
My latest attempt was this, but this set the parent id as the id of the child whose parent I'm trying to add:
UPDATE [dbo].[Node]
SET ParentId = dn.Code
FROM [dbo].[Node] as dn
JOIN @nodes as n ON dn.Code = n.node_code
WHERE dn.TreeId = @treeId AND n.parent_code IN
(SELECT n2.parent_code
FROM [dbo].[Node] as dn2
JOIN @nodes as n2 ON dn2.Code = n2.parent_code
WHERE dn2.TreeId = @treeId)