我有一个带有列的树表ID
,ParentID
并且Hierarchy
想要生成Hierarchy
依赖于的列值ParentID
。为此,我使用触发器。是否存在更好的方法来生成层次列值?
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
功能 :
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
ParentID
对于更新此表也有触发器在更改时再次设置层次结构列。
这个问题的最佳实践是什么?
编辑 1:如果可能,我查找不使用触发器的解决方案。