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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Help with recusive store proc

Author  Topic 

ferrethouse
Constraint Violating Yak Guru

352 Posts

Posted - 2010-05-27 : 15:42:46
It is recursing properly but only down the first branch. So the first call returns 33,37,42,76. It is recursing down the 33 branch but it doesn't come back up and go down the 37, 42, and 76 branch...


ALTER PROCEDURE [dbo].[BuildDepartmentList]
-- Add the parameters for the stored procedure here
@ClientID int,
@ParentID int,
@Depth int = 0,
@SortOrder int = 1
AS
BEGIN
--SET NOCOUNT ON;

DECLARE @DepartmentID int
DECLARE @NextDepth int
DECLARE @MyCursor CURSOR

IF @ParentID = -1
BEGIN
print 'one'
SET @MyCursor = CURSOR FAST_FORWARD
FOR
SELECT DepartmentID FROM Departments
WHERE ClientID = @ClientID AND ParentDeptID = 0
ORDER BY DepartmentName ASC
END
ELSE
BEGIN
print 'two'
print @ParentID
SET @MyCursor = CURSOR FAST_FORWARD
FOR
SELECT DepartmentID FROM Departments
WHERE ClientID = @ClientID AND ParentDeptID = @ParentID
ORDER BY DepartmentName ASC
END

OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @DepartmentID

WHILE @@FETCH_STATUS = 0
BEGIN
print 'three'
print @DepartmentID

SET @SortOrder = @SortOrder + 1

UPDATE DEPARTMENTS SET DEPTH = @Depth, SORTORDER = @SortOrder WHERE DepartmentID = @DepartmentID

SET @NextDepth = @Depth + 1

EXEC BuildDepartmentList @ClientID, @DepartmentID, @NextDepth, @SortOrder

END
END

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-05-27 : 15:59:44
According to BOL:
@@FETCH_STATUS Returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection.

So I suspect that once you hit the bottom of the first branch @@FETCH_STATUS <> 0 and the process ends as it should.

Are you working with SQL 2005 or later? If so, you might want to take a look at Recursive CTEs. If you need more help, check out this link:
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx
Go to Top of Page

ferrethouse
Constraint Violating Yak Guru

352 Posts

Posted - 2010-05-27 : 16:02:17
Actually, it turned out to be a stupid error on my part. I'm missing this line...

FETCH NEXT FROM @MyCursor INTO @DepartmentID

After "EXEC Build...."
Go to Top of Page

Vinnie881
Master Smack Fu Yak Hacker

1231 Posts

Posted - 2010-05-27 : 16:11:01
You should still look at Lamprey's sugestion. A Cte is considered a better alternative.

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=143144


Success is 10% Intelligence, 70% Determination, and 22% Stupidity.
\_/ _/ _/\_/ _/\_/ _/ _/- 881
Go to Top of Page
   

- Advertisement -