concept routine in category sql

appears as: routines, The routines, routine, routines, routine
SQL Server DMVs in Action: Better Queries with Dynamic Management Views

This is an excerpt from Manning's book SQL Server DMVs in Action: Better Queries with Dynamic Management Views.

This example uses routines I’ve created and fully documented in the web links given in the following code sample (so you see, not only is code reuse good but article reuse too). Rather than talk in detail about the contents of these two utilities, I’ll talk about them as black boxes (if you do want to find out more about them, look here for the routine named dba_Block-Tracer: mng.bz/V5E3; and look here for the routine named dba_WhatSQLIs-Executing: mng.bz/uVs3). The code for both of these stored procedures is also available on the webpage for this book on the Manning website. This way you’ll be able to adapt this simple monitor pattern and possibly replace the two utilities with your own favorite utilities. Later in this chapter I’ll go through the code that forms the basis of one of the stored procedures (dba_WhatSQLIsExecuting).

The scripts contained in this chapter will improve the performance of your slow-running SQL queries. They accomplish this by recompiling routines that have become slow, improving the retrieval of data from your indexes, intelligently updating index statistics upon which your optimal query plans will be based, and creating or removing indexes as necessary.

10.2.1. Recompiling routines that are running slower than usual

The script “Finding queries that are running slower than normal,” discussed in section 5.5 of chapter 5, outputs the name of the routine that’s running slower than normal. To automate the routine’s recompilation, we’ll put the output into a temporary table that can be queried to extract the routine name. These routine names can then be wrapped in relevant SQL statements, so that when this script is executed, the identified routines will be marked to be recompiled on their next usage.

Extracting the name of the routine from the output of the script proved a little troublesome, owing to the variability in the format of the routine’s name and the limits of SQL Server’s string function-parsing capabilities, so I decided to write a CLR function to do it. You should deploy this function to your databases if you want to implement this example. Details of how to create and deploy a CLR function are discussed fully in chapter 7, section 7.2. You should follow that example but use the code given in listing 10.1 as the example CLR function.

Here’s the script we use to extract the name of the routine from the SQL text.