Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 More Trees & Hierarchies in SQL

Author  Topic 

calvinfoo
Posting Yak Master

129 Posts

Posted - 2011-12-12 : 03:22:44
Dear Gurus,
http://www.sqlteam.com/article/more-trees-hierarchies-in-sql

I used the same method as in the article in my Org Chart, about 500 employees, with depth of 5 maximum. It works great.

With some slight modification, this is what my table looks like:
USE [AMBU_ALEAVE]
GO
/****** Object: Table [dbo].[Tree] Script Date: 12/12/2011 15:25:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Tree](
[SupervisorEmpID] [nvarchar](50),
[UserEmpID] [nvarchar](50),
[Depth] [tinyint] NULL,
[Lineage] [nvarchar](255)
)

I am a bit stucked right now when I try to further than what it shows:

I want to get know the below:
@EmpID

1. The direct boss:
SELECT * FROM tree WHERE EmpID = @empID

2. The direct Subordinate:
SELECT * FROM tree WHERE SupervisorEmpID = @empID

The above two questions simple, but below questions I am rather still clueless how am I supposed to do that.

3. Select all Supervisors directly above this EmpID.
- If the direct Supervisor is not available, can escalate to higher Superior for the Leave Application

4. Select all peers same as this EmpID under the same direct Supervisor.
- If the EmpID on Sick Leave, the peers can assist to submit the Sick Leave

5. Select all (direct or indirect) subordinates under this EmpID.

Thanks in advance!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-12 : 09:50:28
you need to recursive cte for that

see below link for good explanation of how recursive CTE comes handy here

http://msdn.microsoft.com/en-us/library/ms186243.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

sunnyleoneo
Starting Member

19 Posts

Posted - 2011-12-12 : 12:21:13
Hi,

Please check this simple example of recursive CTE
http://blog.sqlauthority.com/2008/07/28/sql-server-simple-example-of-recursive-cte/
Go to Top of Page
   

- Advertisement -