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 looking for the most elegant approach. I'm mainly going to use it as a simple method to track down Stored Proc hierarchies (without buying a product). I tried cursors within "dynamic sql" and didn't have much luck. I'd like to go about 10 levels deep.
The desired output:
sp_Master_Proc_Name -- sp_Child_Proc_1_Name ---- sp_Sub_Proc_1_Name -- sp_Child_Proc_2_Name -- sp_Child_Proc_3_Name
Its not pretty, but here is the code (and it didn't work as expected)
CREATE PROCEDURE SP_GET_DEPENDENCIES
(
@obj_name varchar(300),
@level int
)
AS
DECLARE @sub_obj_name varchar(300)
IF @level = 1
BEGIN
PRINT @obj_name
END
IF @level = 1
BEGIN
DECLARE the_cursor_1 CURSOR FOR
SELECT DISTINCT REPLICATE('--', @level) + ' ' + 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 the_cursor_1
SET @level = @level + 1
FETCH NEXT FROM the_cursor_1 INTO @sub_obj_name
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @sub_obj_name
EXEC SP_GET_DEPENDENCIES @sub_obj_name, @level
FETCH NEXT FROM the_cursor_1 INTO @sub_obj_name
END
CLOSE the_cursor_1
DEALLOCATE the_cursor_1
END
IF @level = 2
BEGIN
DECLARE the_cursor_2 CURSOR FOR
SELECT DISTINCT REPLICATE('--', @level) + ' ' + 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 the_cursor_2
SET @level = @level + 1
FETCH NEXT FROM the_cursor_2 INTO @sub_obj_name
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @sub_obj_name
EXEC SP_GET_DEPENDENCIES @sub_obj_name, @level
FETCH NEXT FROM the_cursor_2 INTO @sub_obj_name
END
CLOSE the_cursor_2
DEALLOCATE the_cursor_2
END
IF @level = 3
BEGIN
DECLARE the_cursor_3 CURSOR FOR
SELECT DISTINCT REPLICATE('--', @level) + ' ' + 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 the_cursor_3
SET @level = @level + 1
FETCH NEXT FROM the_cursor_3 INTO @sub_obj_name
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @sub_obj_name
EXEC SP_GET_DEPENDENCIES @sub_obj_name, @level
FETCH NEXT FROM the_cursor_3 INTO @sub_obj_name
END
CLOSE the_cursor_3
DEALLOCATE the_cursor_3
END