生成HierarchyID
我想插入像这样的hierarchyId
/
- CEO (Root)/1/
- 采购经理/1/1/
- 采购主管
/2/
- 销售经理/2/1/
- 销售主管
这是我想要使用的层次结构,它是正确的吗?如果是,我该怎么做,任何人都可以给我一些代码片段。
I would like to insert the hierarchyId like this
/
- CEO (Root)/1/
- Purchase Manager/1/1/
- Purchase Executive
/2/
- Sales Manager/2/1/
- Sales Executive
This is what the hierarchy i would like to use, is it right one, if so how can i do this, can any one give me some code snippet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在搜索有关
hierarchyid
数据类型的信息时遇到了这个问题,并且认为对于我之后的其他人来说,看到将hierarchyid
插入为的代码也会很有趣根据问题。我并不是说这些是插入 hierarchyid 的唯一方法,但希望它能帮助那些像我一样以前没有使用此数据类型的经验的人。
使用此表,
您可以使用 Parse 直接插入
hierarchyid 使用字符串路径:
并使用以下查询来检查表
您还可以使用
hierarchyid
数据类型方法 GetRoot 和 GetDescendant 构建层次结构。我发现这种方法比较麻烦,但我认为如果您以编程方式管理层次结构,那么使用这些方法是必要的。一定要查看其他答案中提供的链接,但希望尝试此代码也会有所帮助。
I came across this question while searching for information on the
hierarchyid
data type, and thought it would be interesting for anyone else coming after me to also see code to inserthierarchyid
s as per the question.I do not claim that these are the only ways to insert
hierarchyid
s, but hopefully it will help those who, like me, have no previous experience working with this data type.Using this table,
you can use Parse to directly insert the
hierarchyid
s using the string paths:and use the following query to check the table
You can also use the
hierarchyid
data type methods GetRoot and GetDescendant to build the hierarchy. I found this method to be more cumbersome, but I suppose using these methods is necessary if you are programmatically managing the hierarchy.Definitely check out the links provided in the other answer, but hopefully having this code to try out will help as well.
假设您有一个带有自连接的表模式(如下所示),并且您的 CEO 的 ManagerID 为 NULL。
您可以使用以下递归 CTE 自动生成一组初始的 hierarchyid 值:
然后,向表中添加一个 hierarchyid 列、在其上添加索引,然后通过加入临时表来填充它就变得相当简单了。
但是,请记住,如果您希望在添加 Hierarchyid 数据后保持一致,则应采用非常特定的方式来维护它。
Suppose that you have a table schema with a self-join (as shown below) and that the ManagerID of your CEO is NULL.
You can auto-generate an initial set of hierarchyid values using the following recursive CTE:
It then becomes a fairly trivial matter to add a hierarchyid column to the table, add an index on it, and then populate it by joining to the temp table.
However, bear in mind that if you want the hierarchyid data to remain consistent after you add it, there are very specific ways in which it should be maintained.