How can i get the list of tables in the stored procedure

前端 未结 10 1815
终归单人心
终归单人心 2020-12-01 05:16

There are lot of tables and sp in the db. I find the tables name which are used in the specific sp (stored procedure).

sp_depends %sp_name% not give the

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 06:17

    Here is the sql code for this

    To get list of tables used in a stored procedure

    ;WITH stored_procedures AS (
    SELECT 
    o.name AS proc_name, oo.name AS table_name,
    ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
    FROM sysdepends d 
    INNER JOIN sysobjects o ON o.id=d.id
    INNER JOIN sysobjects oo ON oo.id=d.depid
    WHERE o.xtype = 'P')
    SELECT proc_name, table_name FROM stored_procedures
    WHERE row = 1
    ORDER BY proc_name,table_name
    

    .

    Reverse - To find Stored Procedure Related to Table in Database – Search in All Stored Procedure

    There two ways to this

    ----Option 1
    SELECT DISTINCT so.name
    FROM syscomments sc
    INNER JOIN sysobjects so ON sc.id=so.id
    WHERE sc.TEXT LIKE '%tablename%'
    
    ----Option 2
    SELECT DISTINCT o.name, o.xtype
    FROM syscomments c
    INNER JOIN sysobjects o ON c.id=o.id
    WHERE c.TEXT LIKE '%tablename%'
    

    PS: sp_help and sp_depends does not always return accurate results.

    Reference:

    1. Sql Server Central - Get list of tables used in a stored procedure
    2. SqlAuthority - Find Stored Procedure Related to Table in Database – Search in All Stored Procedure

提交回复
热议问题