473,626 Members | 3,413 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieve Manager/Subordinate hierarchy from Self-Referencing table

Hi SQL Gurus

Could anyone please explain how the following stored procedure can be
amended to retrieve Subordinates in alphabetical order ?

The example below simply retrives records in the order in which they
were entered.

It sounds very easy but I can't sort it out ?

The following code was taken from Narayana Vyas Kondreddi's website
(http://vyaskn.tripod.com/index.htm)

Consider the employee table of an organization, that stores all the
employee records. Each employee is linked to his/her manager by a
manger ID.
CREATE TABLE dbo.Emp
(
EmpID int PRIMARY KEY,
EmpName varchar(30),
MgrID int FOREIGN KEY REFERENCES Emp(EmpID)
)
GO

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

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 PROC dbo.ShowHierarc hy
(
@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.ShowHierarc hy @EmpID
SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE MgrID = @Root AND
EmpID > @EmpID)
END
END
GO
EXEC dbo.ShowHierarc hy 1
GO
---President
------Vice President
---------CEO
---------CTO
------------Group Project Manager
---------------Project Manager 1
------------------Team Leader 1
---------------------Software Engineer 1
---------------------Software Engineer 2
------------------Test Lead 1
---------------------Tester 1
---------------------Tester 2
---------------Project Manager 2
------------------Team Leader 2
---------------------Software Engineer 3
---------------------Software Engineer 4
------------------Test Lead 2
---------------------Tester 3
---------------------Tester 4
---------------------Tester 5
Jul 23 '05 #1
3 5204
Fresh Air Rider (Fr************ *@Hotmail.com) writes:
Could anyone please explain how the following stored procedure can be
amended to retrieve Subordinates in alphabetical order ?


They say that cursors are evil, but what is evil is iterative solutions,
and you already have an iterative solution. And of all ways to iterate,
in my opinion, the cursor is often the best. So here is a way to
tackle the problem:

CREATE PROC dbo.ShowHierarc hy
(
@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

DECLARE emp_cur CURSOR LOCAL FOR
SELECT EmpID FROM dbo.Emp WHERE MgrID = @Root ORDER BY EmpName
OPEN emp_cur

WHILE 1 = 1
BEGIN
FETCH emp_cur INTO @EmpID
IF @@fetch_status <> 0
BREAK
EXEC dbo.ShowHierarc hy @EmpID
END
DEALLOCATE emp_cur
END
GO

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #2
Hi Erland

As I said before, that iterative solution wasn't my own code, it was
taken straight from from Narayana Vyas Kondreddi's website
(http://vyaskn.tripod.com/index.htm).

Your solution looks very interesting and I will certainly give it a
try.

Many thanks for your suggestion.

Best wishes
David
Jul 23 '05 #3
Fresh Air Rider (Fr************ *@Hotmail.com) writes:
As I said before, that iterative solution wasn't my own code, it was
taken straight from from Narayana Vyas Kondreddi's website
(http://vyaskn.tripod.com/index.htm).


Yeah, I know. I added the introduction about evil to defend the use
of cursors.

In fact, had Vyas used a cursor for his example, you would probably
not have asked your question, but found the answer yourself!


--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2250
by: John J. Lee | last post by:
I'm trying to change a base class of a big class hierarchy. The hierarchy in question is 4DOM (from PyXML). 4DOM has an FtNode class that defines __getattr__ and __setattr__ that I need to override. Lots of classes derive from FtNode, often through further base classes, eg. HTMLDirectoryElement --> HTMLElement --> Element --> FtNode There are many leaf classes like HTMLDirectoryElement. The problem
0
1256
by: Tero Saarni | last post by:
Hi, I have a module with several test case classes which each have several test methods: class Foo(unittest.TestCase): def testMethod1(self): def testMethod2(self): class Bar(unittest.TestCase):
1
1259
by: Scott Simpson | last post by:
I can build portions of DOM trees with jdom and xpathapi and using "new Element()" and "appendChild()" or "addContent()". Which function do I use to get a whole portion of a DOM tree though? For example, suppose I have <foo> <bar name="dopey"> <snafu> Text </snafu> </bar>
13
1749
by: Ray Allison | last post by:
Is it bad practice to use 'Select * ' from a security perspective? Thanks for any advice. Ray
0
2069
by: Kamilche | last post by:
''' event.py An event manager using publish/subscribe, and weakrefs. Any function can publish any event without registering it first, and any object can register interest in any event, even if it doesn't exist yet. The event manager uses weakrefs, so lists of listeners won't stop them
8
1743
by: Jeffrey Barish | last post by:
I believe that the answer to my question is no, but I want to be sure that I understand this issue correctly: Suppose that there are two classes defined as follows: class A(object): def f1(self): print 'In A.f1, calling func' self.func() def func(self):
4
1812
by: Pupeno | last post by:
Hello, I want to jump over a method in the class hierarchy, that is: If I have class A(object), clas B(A), class C(B) and in C, I want a method to do exactly what A does but not what B does in its reimplementation, would it be correct to do: super(A, super(B, self)).method() in C ? Thank you. -- Pupeno <pupeno@pupeno.com(http://pupeno.com)
10
3564
by: John Nagle | last post by:
Here are three network-related exceptions. These were caught by "except" with no exception type, because none of the more specific exceptions matched. This is what a traceback produced: 1. File "D:\Python24\lib\socket.py", line 295, in read data = self._sock.recv(recv_size) timeout: timed out
7
2676
by: =?Utf-8?B?UVNJRGV2ZWxvcGVy?= | last post by:
I have a C# logging assembly with a static constructor and methods that is called from another C# Assembly that is used as a COM interface for a VB6 Application. Ideally I need to build a file name based on the name of the VB6 application. A second choice would be a file name based on the # COM interface assembly. I have tried calling Assembly.GetCallingAssembly() but this fails when I use the VB6 client. Is there a way to get this...
4
1697
by: Daniel | last post by:
Hello, I need to access the code inside of a context manager, i.e. the call to with myManager(v=5) as x: a=b c=sin(x) should cause the following output (minus the first line, if that's easier):
0
8272
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8205
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8370
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8514
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5579
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4094
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4208
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2632
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1516
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.