此代码涉及递归存储过程调用和避免游标名称冲突的“不太好”的方法。最后我不在乎它是否使用游标。只是寻找最优雅的方法。我主要将其用作追踪存储过程层次结构的简单方法(无需购买产品)。我在“动态 sql”中尝试了游标,但运气不佳。我想深入大约 10 个级别。
所需的输出:
sp_Master_Proc_Name -- sp_Child_Proc_1_Name ---- sp_Sub_Proc_1_Name -- sp_Child_Proc_2_Name -- sp_Child_Proc_3_Name
它不漂亮,但这里是代码(它没有按预期工作)
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