(
EmpID int PRIMARY KEY,
EmpName varchar(30),
MgrID int FOREIGN KEY REFERENCES Emp(EmpID)
)
GO
Insert few record into table
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
Create sql function
create FUNCTION [dbo].[ShowHierarchy]
(
@Root bigint
)
RETURNS
@menutable TABLE(EmpName varchar(max),MgrID int,EmpID int)
AS
BEGIN
DECLARE @EmpID int, @EmpName varchar(30),@MgrID int, @rootid bigint
set @rootid =@Root
SELECT @EmpID=EmpID,@EmpName=EmpName,@MgrID=MgrID FROM dbo.Emp WHERE EmpID = @Root
-- SET @EmpName = (SELECT EmpName FROM dbo.Emp WHERE EmpID = @Root)
if(@EmpName is not null)
begin
insert into @menutable select REPLICATE(' ', @@NESTLEVEL * 4) + @EmpName,@MgrID,@EmpID
end
SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @Root)
WHILE @EmpID IS NOT NULL
BEGIN
insert into @menutable select * from dbo.ShowHierarchy(@EmpID)
SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @rootid AND EmpID > @EmpID)
END
return
END
//call this function from where you want
Select * from dbo.ShowHierarchy(0)
nice way for n level items
ReplyDeletethanking you for providing cooding.
ReplyDeletephp developer india