【问题标题】:Stored Procedure with dependent table not exist具有依赖表的存储过程不存在
【发布时间】:2014-07-08 09:19:03
【问题描述】:

我们如何从数据库中不存在其依赖表的 Microsoft SQL 服务器检索所有存储过程?

我只是解释一下......

我有一个包含数百个表和存储过程的数据库。在开发时间的同时,我只是添加了更多的表并从数据库中删除了一些以前的表,但是存储过程不依赖于这个表。结果是,当我生成上述数据库的脚本并尝试在另一个数据库中恢复它时,由于表不存在而导致错误。

【问题讨论】:

    标签: sql sql-server stored-procedures


    【解决方案1】:

    下面的查询应该会给你你所追求的。

    SELECT  OBJECT_NAME(sed.referencing_id) AS referencing_entity_name, 
            sed.referenced_entity_name
    FROM sys.objects AS o
    INNER JOIN sys.sql_expression_dependencies AS sed ON sed.referencing_id = o.object_id
    WHERE o.type = 'P'
    and not exists (select 1 from INFORMATION_SCHEMA.COLUMNS 
                    where table_name = referenced_entity_name)
    and referenced_id is null
    

    它使用 sys.objects 来查找存储过程并连接到 sys.sql_expression_dependencies 来查找这些 SP 的依赖关系。然后它根据表是否存在于 INFORMATION_SCHEMA.COLUMNS 中过滤依赖关系。

    有关查找依赖项的更多信息,请参阅 MSDN -http://msdn.microsoft.com/en-us/library/ms345404%28v=sql.120%29.aspx

    请注意,sys.sql_expression_dependencies 仅存在于 SQL Server 2008 及更高版本中。您没有说明您使用的是哪个版本,但如果您使用的是 2005,则需要使用 sys.sql_dependencies 而不是 sys.sql_expression_dependencies。不幸的是,这不是直接交换,因为列不同,但更多信息可以在 MSDN 上找到 - http://msdn.microsoft.com/en-us/library/ms174402%28v=SQL.90%29.aspx

    【讨论】:

    • 良好的 SQL 语句.. 备注:当存储过程调用现有存储过程时,它也会显示在此列表中。
    【解决方案2】:

    亲爱的,你没有提到你的 sqlserver 版本。

    但是你可以通过2个查询来实现

    -- first query to get all procedure name
        SELECT routine_name, routine_type FROM INFORMATION_SCHEMA.ROUTINES where ROUTINE_TYPE = 'PROCEDURE' order by ROUTINE_NAME asc
    
    --you can loop of above and pass the each procedure name to this second query. If zero return , then no dependency
        SELECT referencing_schema_name, referencing_entity_name, referencing_id, referencing_class_desc, is_caller_dependent
        FROM sys.dm_sql_referencing_entities ('dbname.procedureName', 'OBJECT'); 
    

    http://www.mssqltips.com/sqlservertip/1294/listing-sql-server-object-dependencies/

    http://msdn.microsoft.com/en-IN/library/ms345404.aspx

    Stored procedure dependencies in SQL Server Management Studio

    http://sqlhints.com/2013/05/06/how-to-find-referenceddependent-objects-like-table-function-etc-of-a-stored-procedurefunction-in-sql-server/

    Determining the dependencies of a stored procedure.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      相关资源
      最近更新 更多