Tuesday, June 25, 2013

Create multiple root node using HierarchyId column

CREATE TABLE [Entity](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [Hierarchy] [hierarchyid] NOT NULL
 CONSTRAINT [PK_Entity] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)
) ON [PRIMARY]

INSERT INTO [Entity]
      ([Name]
      ,[Hierarchy])
     VALUES
      ('Root A'
      ,hierarchyid::GetRoot().GetDescendant(NULL,NULL))


-- Create the second 'root'
INSERT INTO [Entity]
      ([Name]
      ,[Hierarchy])
     VALUES
      ('Root B'
      ,hierarchyid::GetRoot().GetDescendant((select MAX(hierarchy) from entity where hierarchy.GetAncestor(1) = hierarchyid::GetRoot()),NULL))

No comments:

Post a Comment