This code involves a recursive Stored Procedure call and a \"not so great\" method of avoiding cursor name collision. In the end I don\'t care if it uses cursors or not. Just lo
for ms sql server you can use CURSOR LOCAL, then the cursor is local to the sproc call and your code becomes much simpler:
CREATE PROCEDURE uspPrintDependencies
(
@obj_name varchar(300),
@level int
)
AS
SET NOCOUNT ON
DECLARE @sub_obj_name varchar(300)
if @level > 0 begin
PRINT Replicate(' ',@level) + @obj_name
end
else begin
PRINT @obj_name
end
DECLARE myCursor CURSOR LOCAL FOR
SELECT
DISTINCT c.name
FROM dbo.sysdepends a
INNER JOIN dbo.sysobjects b ON a.id = b.id
INNER JOIN dbo.sysobjects c ON a.depid = c.id
WHERE b.name = @obj_name
OPEN myCursor
SET @level = @level + 1
FETCH NEXT FROM myCursor INTO @sub_obj_name
WHILE @@FETCH_STATUS = 0 BEGIN
EXEC uspPrintDependencies @sub_obj_name, @level
FETCH NEXT FROM myCursor INTO @sub_obj_name
END
CLOSE myCursor
DEALLOCATE myCursor
GO
See this Stackoverflow question for a discussion of sorting querying table foreign key dependencies by depth - which is a similar problem to the one you're discussing. There are at least two working solutions to that problem in the answers and the only real difference to what you're doing is the tables they're crawling. This posting has a DB reverse engineering script that shows how to use a lot of the main data dictionary tables.