Sql-server – Adding logging statements at start and end of all stored procedures

loggingsql serversql-server-2012stored-procedures

I would like to capture stored procedure execution details which would require altering existing procedures to perform an INSERT at the start and an UPDATE at the end.

I recall finding a blog article some time ago that demonstrated adding statements to the start/end of stored procedures but cannot find it.

How could I make these changes programmatically either in C# or T-SQL ensuring the original stored procedure definition works as expected?

Edit: As a minimum I want to capture the user executing, the stored procedure name, start and end times. Parameters and stored procedure definition are optional.

Best Answer

I would advise against programmatically modifying all the stored procedures in a database like that. Trying to ensure no edge-case causes a modification to be made erroneously will prove quite difficult.

Instead of modifying all the stored procedures, why not use Extended Events to capture the information you're interested in. This will

  1. Not impact performance nearly as much
  2. Allow you to enable/disable monitoring as required, without modifying any stored procedures.
  3. Not affect execution plans for the stored procedures.

SQLTips has a good example of several ways to capture stored procedure execution history without modifying the stored procedures.