T-SQL Puzzler - Crawling Object Dependencies

前端 未结 2 1780
面向向阳花
面向向阳花 2021-02-06 19:19

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

2条回答
  •  盖世英雄少女心
    2021-02-06 19:32

    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
    

提交回复
热议问题