SQL [hierarchyid] type: How to dynamically insert hierarchical data, hierarchyid level

Source: Internet
Author: User

SQL [hierarchyid] type: How to dynamically insert hierarchical data, hierarchyid level

[Hierarchyid] is a good data type and provides a convenient and high-performance tree-based query. I have found a lot of information on the Internet and have not talked about how to perform dynamic insertion, I carefully read the document from MSDN and wrote a DEMO.

Create table EmployeeOrg (OrgNode hierarchyid primary key clustered, OrgLevel AS OrgNode. getLevel (), EmployeeID int unique not null, EmpName varchar (20) not null, Title varchar (20) NULL); goCREATE PROC AddEmp (@ mgrid int, @ empid int, @ e_name varchar (20), @ title varchar (20) as begin declare @ mOrgNode hierarchyid, @ lc hierarchyid SELECT @ mOrgNode = OrgNode FROM EmployeeOrg WHERE EmployeeID = @ mgrid set transaction isolation level serializable begin transaction select @ lc = max (OrgNode) FROM EmployeeOrg WHERE OrgNode. getAncestor (1) = @ mOrgNode; INSERT EmployeeOrg (OrgNode, EmployeeID, EmpName, Title) VALUES (@ mOrgNode. getDescendant (@ lc, NULL), @ empid, @ e_name, @ title) COMMITEND; go -- INSERT root INSERT EmployeeOrg (OrgNode, EmployeeID, EmpName, Title) VALUES (hierarchyid :: getRoot (), 1, 'lamps, 'marketing manager') go -- random number declare @ p1 intselect @ p1 = convert (int, 100000000 * rand ()) declare @ p2 intselect @ p2 = convert (int, 100000000 * rand () -- Insert the software department subset EXEC AddEmp 1, @ p1, 'r & D department leader ', 'marketing specialist '; EXEC AddEmp 1, @ p2, 'test Team Leader ', 'marketing specialist'; goselect * from EmployeeOrg

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.