Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

sql server - How can I get the list of tables in the stored procedure?

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 desire result. I am also used INFORMATION_SCHEMA.TABLES,INFORMATION_SCHEMA.ROUTINES tables.

But the result is not full fill my requirment.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The two highest voted answers use a lot of deprecated tables that should be avoided.
Here's a much cleaner way to do it.

Get all the tables on which a stored procedure depends:

SELECT DISTINCT p.name AS proc_name, t.name AS table_name
FROM sys.sql_dependencies d 
INNER JOIN sys.procedures p ON p.object_id = d.object_id
INNER JOIN sys.tables     t ON t.object_id = d.referenced_major_id
ORDER BY proc_name, table_name

Works with MS SQL SERVER 2005+

List of Changes:

  • sysdepends should be replaced with sys.sql_dependencies
    • The new table uses object_id instead of id
    • The new table uses referenced_major_id instead of depid
  • Using sysobjects should be replaced with more focused system catalog views
  • Also, there is really no need for a CTE which uses ROW_NUMBER() just in order to make sure we only have one of each record set returned. That's what DISTINCT is there for!

    • In fact, SQL is smart enough to use DISTINCT behind the scenes.
    • I submit into evidence: Exhibit A. The following queries have the same Execution Plan!

      -- Complex
      WITH MyPeople AS (
        SELECT id, name,
        ROW_NUMBER() OVER(PARTITION BY id, name ORDER BY id, name) AS row
        FROM People)
      SELECT id, name
      FROM MyPeople
      WHERE row = 1
      
      -- Better
      SELECT DISTINCT id, name
      FROM People
      

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...