SgDotNet
Singapore Professional .NET User Group -For Cool Developers

Recursive Stored Procedure

rated by 0 users
This post has 2 Replies | 1 Follower

Top 50 Contributor
Posts 67
eric_tcp Posted: 10-03-2007 6:11 PM

Hi all,

Any one out there familiar with Stored Procedure can  advise me on how to create recursive stored procedure and returns the data?

In my table there are data which have higher level, eg:

Manager > Supervisor > Staff

I like to pass in the manager id, and i able to get the supervisor and staff id

.

 

Thanks. 

Top 25 Contributor
Posts 157

It is a little unusual to be using recursive stored procedure when you can actually query to get the results in a single stored procedure. So, I assume that you are going to pass only the manager ID, which results in a list of supervisor IDs, and for each supervisor, which in turn results in a list of staff IDs?

Anyways, to call a stored procedure within a stored procedure, try this:

DECLARE @SupID INT
EXEC @SupID = uspGetSupervisorID @ManagerID

But looping in SQL is not advisable and should be avoided. Performance will be better if you just simply use a single statement to get the data you need. If assuming the data is stored in a single table tblUser (where SupID mean superior ID), try this:

SELECT man.UserID AS ManagerID, sup.UserID AS SupervisorID, stf.UserID AS StaffID
FROM tblUser AS man JOIN tblUser AS sup ON man.UserID = sup.SupID
JOIN tblUser AS stf ON sup.UserID = stf.SupID
WHERE man.UserID = @ManagerID

Top 10 Contributor
Posts 2,284

You may wanna check out Common Table Expressions (CTE) and see if it helps your purposes.

http://www.4guysfromrolla.com/webtech/071906-1.shtml

The melody of logic will always play out the truth. ~ Narumi Ayumu, Spiral

Page 1 of 1 (3 items) | RSS
Copyright SgDotNet 2004-2008
Powered by Community Server (Commercial Edition), by Telligent Systems