Recursive for Microsoft SQL Server 7.0


1. Create Table for Test
CREATE TABLE dbo.Emp
(
EmpID int PRIMARY KEY,
EmpName varchar(30),
MgrID int FOREIGN KEY REFERENCES Emp(EmpID)
)
GO


2. Create Index
CREATE NONCLUSTERED INDEX NC_NU_Emp_MgrID ON dbo.Emp(MgrID)
GO


3. Insert Sample Data
INSERT dbo.Emp SELECT 1, 'President', NULL
INSERT dbo.Emp SELECT 2, 'Vice President', 1
INSERT dbo.Emp SELECT 3, 'CEO', 2
INSERT dbo.Emp SELECT 4, 'CTO', 2
INSERT dbo.Emp SELECT 5, 'Group Project Manager', 4
INSERT dbo.Emp SELECT 6, 'Project Manager 1', 5
INSERT dbo.Emp SELECT 7, 'Project Manager 2', 5
INSERT dbo.Emp SELECT 8, 'Team Leader 1', 6
INSERT dbo.Emp SELECT 9, 'Software Engineer 1', 8
INSERT dbo.Emp SELECT 10, 'Software Engineer 2', 8
INSERT dbo.Emp SELECT 11, 'Test Lead 1', 6
INSERT dbo.Emp SELECT 12, 'Tester 1', 11
INSERT dbo.Emp SELECT 13, 'Tester 2', 11
INSERT dbo.Emp SELECT 14, 'Team Leader 2', 7
INSERT dbo.Emp SELECT 15, 'Software Engineer 3', 14
INSERT dbo.Emp SELECT 16, 'Software Engineer 4', 14
INSERT dbo.Emp SELECT 17, 'Test Lead 2', 7
INSERT dbo.Emp SELECT 18, 'Tester 3', 17
INSERT dbo.Emp SELECT 19, 'Tester 4', 17
INSERT dbo.Emp SELECT 20, 'Tester 5', 17
GO


4. Create Store Procedure
CREATE PROC dbo.ShowHierarchy
(
 @Root int
)
AS
BEGIN
 SET NOCOUNT ON
 DECLARE @EmpID int, @EmpName varchar(30)


 SET @EmpName = (SELECT EmpName FROM dbo.Emp WHERE EmpID = @Root)
 PRINT REPLICATE('-', @@NESTLEVEL * 4) + @EmpName


 SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @Root)


 WHILE @EmpID IS NOT NULL
 BEGIN
  EXEC dbo.ShowHierarchy @EmpID
  SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @Root AND EmpID > @EmpID)
 END
END
GO


5. Run Store Procedure
EXEC dbo.ShowHierarchy 1
GO

Comments

Popular posts from this blog

การตั้งเวลาระหว่าง Server และ Client

วิธีตั้งค่า NTP บน Primary Domain Controller

Installation and Run Node.JS on IIS