SQL Server – Organizing Stored Procedures and Views

sql serversql-server-2008-r2stored-procedures

I have a database with 112 stored procs, 7 views and 88 tables.
The problem is over time I have created tables and stored procs as I needed without taking the time to think about what I might be doubling up on work. I already know I have a couple of reports I generate that use essentially the same information but are pulling from two different tables. I am trying to bring everything down to as few tables and stored procs as possible.

The only thing I can think of is running a query that queries the stored procs to see what tables they all reference, this should get me a list of all the tables that are actually even being used any more.

Also I would want to know which procs are actually being run so a query that shows last run time for each proc.

Best Answer

We have all been there. It sounds like you don't have a specific question, but just need some help getting started. You need to learn about the sys tables available in SQL Server and the DMV's. They are insanely useful.

Ones that will be helpful in your case:

  • sys.procedures - gets you a list of your stored procedures
  • sys.object - gets a list of all objects
  • sys.dm_exec_procedure_stats - gives stats of your stored procedures, how many times they executed, when the last execute was, etc.
  • sys.dm_sql_referenced_entities - returns entities that are referenced by the object you provide (pass a stored procedure name and it will return all the tables and views it hits)
  • sys.dm_sql_referencing_entities - returns entities that refer to the object you pass (pass a table name and it will return all the stored procedures that hit that table)