How do I identify views with broken dependencies in SQL Server?

前端 未结 5 1824
悲哀的现实
悲哀的现实 2021-01-02 01:40

We have a large number of views in an inherited database which some of them are missing dependencies (table or even other views)?

What\'s the best way to identify th

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 02:41

    Adrian Iftode's solution is good, but fails if there are views that are not associated with the default schema. The following is a revised version of his solution that takes schema into account, whilst also providing error information against each failing view (tested on SQL Server 2012):

    DECLARE @stmt       NVARCHAR(MAX) = '';
    DECLARE @vw_schema  NVARCHAR(255);
    DECLARE @vw_name    NVARCHAR(255);
    
    CREATE TABLE #badViews 
    (    
          [schema]  NVARCHAR(255)   
        , name      NVARCHAR(255)
        , error     NVARCHAR(MAX) 
    );
    
    CREATE TABLE #nullData
    (  
        null_data VARCHAR(1)
    );
    
    DECLARE tbl_cursor CURSOR FORWARD_ONLY READ_ONLY
    FOR
        SELECT
              SCHEMA_NAME(schema_id) AS [schema]
            , name
        FROM
            sys.objects 
        WHERE
            [type] = 'v';
    
    OPEN tbl_cursor;
    FETCH NEXT FROM tbl_cursor INTO @vw_schema, @vw_name;
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @stmt = CONCAT(N'SELECT TOP 1 NULL FROM ', @vw_schema, N'.', @vw_name);
    
        BEGIN TRY
          -- silently execute the "select from view" query
            INSERT INTO #nullData EXECUTE sp_executesql @stmt;
        END TRY 
        BEGIN CATCH
            INSERT INTO #badViews ([schema], name, error)
            VALUES (@vw_schema, @vw_name, ERROR_MESSAGE());
        END CATCH
    
        FETCH NEXT FROM tbl_cursor INTO @vw_schema, @vw_name;
    END
    
    CLOSE tbl_cursor;
    DEALLOCATE tbl_cursor;    
    
    -- print the views with errors when executed
    SELECT * FROM #badViews;
    
    DROP TABLE #badViews;
    DROP TABLE #nullData;
    

提交回复
热议问题