1: --Create Table Employee
2: CREATE TABLE Employee
3: (
4: EmpId int,
5: EmpBossId HIERARCHYID,
6: --GetLevel --> returns the level of the current node in the hierarchy
7: EmpLevel as EmpBossId.GetLevel() PERSISTED,
8: EmpCode varchar(50),
9: EmpName varchar(50)
10: );
11: Go
12: -- Create Insert Store Procedure
13: Alter PROCEDURE Employee_isp
14: @empid int,
15: @empbossid int,
16: @empcode varchar(50),
17: @empname varchar(50)
18: AS
19: BEGIN
20: declare @hid HIERARCHYID,@empboss_hid HIERARCHYID,@last_hid HIERARCHYID
21:
22: if @empbossid = 0
23: begin
24: set @hid = HIERARCHYID::GetRoot();
25: end
26: else
27: begin
28:
29: SET @empboss_hid = (SELECT EmpBossId FROM Employee WHERE empid = @empbossid);
30: SET @last_hid = (SELECT MAX(EmpBossId) FROM Employee WHERE EmpBossId.GetAncestor(1)= @empboss_hid);
31: SET @hid = @empboss_hid.GetDescendant(@last_hid, NULL);
32: end
33: INSERT INTO Employee(empid, EmpBossId, EmpCode, EmpName)
34: VALUES(@empid, @hid, @empcode, @empname);
35: END
36: GO
37: --insert data
38: -- A1
39: -- AL1 AR1
40: -- AL1L AL1R AR1L AR1R
41: --
42: --
43: EXEC Employee_isp @empid = 1, @empbossid = 0, @empcode = 'A1' ,@empname = 'A1';
44: EXEC Employee_isp @empid = 2, @empbossid = 1, @empcode = 'AL1' ,@empname = 'AL1';
45: EXEC Employee_isp @empid = 3, @empbossid = 1, @empcode = 'AR1' ,@empname = 'AR1';
46: EXEC Employee_isp @empid = 4, @empbossid = 2, @empcode = 'AL1L' ,@empname = 'AL1L';
47: EXEC Employee_isp @empid = 5, @empbossid = 2, @empcode = 'AL1R' ,@empname = 'AL1R';
48: EXEC Employee_isp @empid = 6, @empbossid = 3, @empcode = 'AR1L' ,@empname = 'AR1L';
49: EXEC Employee_isp @empid = 7, @empbossid = 3, @empcode = 'AR1R' ,@empname = 'AR1R';