如何获取特定存储过程中使用的所有表名?

时间:2017-04-03 06:24:34

标签: sql sql-server

我需要获取在特定存储过程中使用的所有数据库表名称吗?

举个例子,我有一个存储过程,如下所示。

CREATE PROCEDURE [dbo].[my_sp_Name]
    @ID INT = NULL
AS
BEGIN

    SELECT ID, NAME, PRICE

    FROM tbl1
    INNER JOIN tbl2 ON tbl1.ProductId = tbl2.ProductId
    LEFT JOIN tbl3 ON tbl2.ProductSalesDate = tbl3.ProductSalesDate
    LEFT JOIN tbl4 ON tbl1.ProductCode = tbl4.ItemCode
END

预期输出:

Used_Table_Name

  1. TBL1
  2. TBL2
  3. TBL3
  4. tbl4
  5. 任何人都可以建议吗?

2 个答案:

答案 0 :(得分:3)

下面的查询将帮助您在存储过程中使用数据库表。

;WITH stored_procedures AS (  
    SELECT 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' AND o.name = 'my_sp_Name'
)  
SELECT Table_name AS 'Used_Table_Name' FROM stored_procedures  
WHERE row = 1

答案 1 :(得分:2)

使用以下脚本在商店过程中获取表名:

  SELECT DISTINCT [object_name] = SCHEMA_NAME(o.[schema_id]) + '.' + o.name
        , o.type_desc
  FROM sys.dm_sql_referenced_entities ('[dbo].[Your_procedurename]',  
  'OBJECT')d
  JOIN sys.objects o ON d.referenced_id = o.[object_id]
  WHERE o.[type] IN ('U', 'V')