I have a tree table with the ID , ParentID and Hierarchy columns and you want to generate a Hierarchy column value depending on the ParentID . for this purpose i use triggers. Is there a better way to generate a hierarchy column value?
ALTER TRIGGER [TR_MyTable_BeforInsert] ON [MyTable] INSTEAD OF INSERT AS BEGIN SET NOCOUNT ON; Declare @Name NVarChar(100), @ParentID Int Declare DACategory Cursor For Select A.Name, A.ParentID From Inserted A OPEN DACategory FETCH NEXT FROM DACategory INTO @Name, @ParentID While @@FETCH_STATUS=0 Begin Insert Into MyTable (Name, ParentID, Hierarchy) Values (@Name, @ParentID, dbo.F_MyTableGetHID(NULL, @ParentID)) FETCH NEXT FROM DACategory INTO @Name, @ParentID End Close DACategory Deallocate DACategory END
Function:
ALTER FUNCTION [F_MyTableGetHID] ( @ID int, @ParentID int ) RETURNS HierarchyID AS BEGIN Declare @RootHID HierarchyID, @LastHID HierarchyID IF (@ParentID IS NULL)Begin Set @RootHID = HierarchyID::GetRoot() Select @LastHID = Max(Hierarchy) From MyTable Where ParentID IS NULL End Else Begin Select @RootHID = Hierarchy From MyTable Where ID = @ParentID select @LastHID = Max(Hierarchy) From MyTable where ParentID = @ParentID End return @RootHID.GetDescendant(@LastHID, NULL) END
there is also a trigger for updating this table to set the Hierarchy column again when the ParentID Changed.
what are the best methods for this problem?
EDIT 1 . I am looking for a solution that does not use a trigger, if possible.
mehdi lotfi
source share