Find broken objects in SQL Server

前端 未结 11 521
孤独总比滥情好
孤独总比滥情好 2020-12-02 17:26

Is there a tool that will find all objects in SQL Server (functions, procs, views) that cannot possibly work because they refer to objects that don\'t exist?

11条回答
  •  [愿得一人]
    2020-12-02 18:02

    The two previous solutions here are interesting, but both failed on my test databases.

    The original Michael J Swart script produced a huge number of false positives for me, far too many to wade through. Rick V.'s solution here was better - the only false positives it gave were for cross-database references.

    There's a comment on the Michael J Swart article by RaduSun which gives a solution that I can't yet break though! This is it, tweaked mildly for readability and my purposes, but credit to RaduSun for the logic.

    SELECT 
        QuoteName(OBJECT_SCHEMA_NAME(referencing_id)) + '.' 
            + QuoteName(OBJECT_NAME(referencing_id)) AS ProblemObject,
        o.type_desc,
        ISNULL(QuoteName(referenced_server_name) + '.', '')
        + ISNULL(QuoteName(referenced_database_name) + '.', '')
        + ISNULL(QuoteName(referenced_schema_name) + '.', '')
        + QuoteName(referenced_entity_name) AS MissingReferencedObject
    FROM
        sys.sql_expression_dependencies sed
            LEFT JOIN sys.objects o
                ON sed.referencing_id=o.object_id
    WHERE
        (is_ambiguous = 0)
        AND (OBJECT_ID(ISNULL(QuoteName(referenced_server_name) + '.', '')
        + ISNULL(QuoteName(referenced_database_name) + '.', '')
        + ISNULL(QuoteName(referenced_schema_name) + '.', '')
        + QuoteName(referenced_entity_name)) IS NULL)
    ORDER BY
        ProblemObject,
        MissingReferencedObject
    

提交回复
热议问题