SQL Server – How to Find Usage of Each Object in Database

database-designerwinsql serversql-server-2008

I am with the task of taking an old SQL Server database and identify all of it's objects and their relationships, because the one who made it did not bother to use any foreign key, he just made all relations inside the code.

So my mission is to identify usages, relationships and make a graphic model, which I think I will use ERwin7 to do it.

I stated today taking every table name and searching it in the source-code and sql metadata. I open all those files in separated instances of Notepad++ and search to see if anyone really uses that table in the source-code or in any stored procedure or function. But there are 1500+ c# files and 857 objects in the database.

  • Is there a better way to do that?
  • Is there a tool to tell me where each table is used in the code and in the database without the need of Ctrl+F for each table name or other objects I will also check?
  • Is ER-win a reasonable choice for doing the re-modeling?

Best Answer

I'm afraid I can't help with the C# code or Erwin but you can use this query for the SQL Code

SELECT * FROM sys.dm_sql_referencing_entities('dbo.ABC', 'OBJECT') 

The above query will return a list of all code objects (SPs, Functions etc) in the database that reference the object named in the initial parameter. The two part name is required. It will not unfortunately list objects that are not in the current database but it should get you started.

If you need it you can also go the other direction.

SELECT * FROM sys.dm_sql_referencing_entities('dbo.ABC', 'OBJECT') 

In this case the first parameter dbo.ABC would be a piece of code (an SP for example) and the DMO will return a list of all objects used by that SP (or whatever). From what I can tell this one WILL return objects that are in different databases or servers.

I discussed these and some other (older) options here: http://sqlstudies.com/2012/10/26/how-do-i-find-all-stored-procedures-or-views-that-use-a-specific-table/