Product articles
SQL Prompt
Query Performance
How to Test SQL Server Functions and…

How to Test SQL Server Functions and Procedures using SQL Prompt

Phil Factor shows how to create a table of input values versus expected results, and then use it to unit test your SQL stored procedures and functions and verify that they always produce the correct results. He uses SQL Prompt to make this task much simpler.

Guest post

This is a guest post from Phil Factor. Phil Factor (real name withheld to protect the guilty), aka Database Mole, has 30 years of experience with database-intensive applications.

Despite having once been shouted at by a furious Bill Gates at an exhibition in the early 1980s, he has remained resolutely anonymous throughout his career.

He is a regular contributor to Simple Talk and SQLServerCentral.

When writing functions or procedures, a common chore is to devise and implement the tests that ensure that the routine always works as expected. The best way to do this is to define the tests in a batch that is attached to the CREATE or ALTER script. for the routine This isn’t just to prevent you from making any obvious mistakes, as you develop the routine, but also to prevent anyone else from subsequently altering it when they are ‘feeling lucky’, without doing manual unit tests.

From my experience, it has saved me from embarrassment, and caught out a few colleagues who sought to improve my work, without considering the unpleasant side-effects. It is often a life-saver when working on performance improvements.

Testing all your SQL queries and routines in this way can take time to do properly, but there is a very handy feature in SQL Prompt called “Script as Insert” that considerably lightens the workload. It allows you to refactor the results of a query into a INSERT INTO…VALUES statement that save the results into a temporary table. Let me explain, by way of an example.

Basic testing for a function to trim leading zeros

Listing 1 is a routine that removes leading zeros from a string.

Listing 1

You now have the problem of testing it. It is a good practice to attach a batch of tests to the build script, to catch all obvious mistakes. Generally, you will want to pass in to the routine parameters that contain known values, and examine the result to ensure that the routine does what is expected and doesn’t do anything unexpected.

Listing 2, appended directly to the end of Listing 1, will run a few tests, checking for various obvious problems, every time we create or alter the object.

Listing 2

What I’ve done is to create a table-source, using a multi-row VALUES statement. This gives me known input. The second string in the pair is the expected output value, in each case. All I need to do is to check the expected output with what was actually output, and raise an error if there was a difference. This is done to alert the build process that a basic test is failed.

Building out the test data using SQL Prompt

I haven’t really got enough tests to build confidence. I need at least fifty, including some created with random data, so I start to build a table of ‘before’ and ‘after’ values.

Listing 3

Which gives something like this…

Input values for a routine versus expected output.

Doesn’t look much does it? Now, with the power of cut ‘n paste, a few seconds later we have fifty rows, which should be sufficient.

Building out the test data set
Specify grid output, execute the newly-fattened query. Now, we want  to convert the SELECT results into an multi-values INSERT script for a temporary table. To do that, select the entire grid by clicking on the top left square, then right-click on the grid, to find the SQL Prompt hidden treasure, Script as INSERT:

Using Script As Insert to save query results to a table

This feature converts this lot into a multi-row VALUES expression that we can need for in our test harness. However, it first needs a bit of manual formatting. I used a regex: search for )\s,\s\r\n, which is a close bracket, any number of spaces, a comma, any number of spaces, followed by a windows line end, and replaced it with ). The result looks like this:

The multi-row VALUES expression generated by SQL Prompt

Running the tests

So now we have a test set of over fifty tests, which we add to all the obvious edge cases.

Listing 4

The next stage is to go through these tests in detail, to be certain that they are correct. You might need to involve a business stakeholder and test engineer to agree that the output is correct for each input (it is amazing what sort of bugs can emerge from this process!)

Once you’re sure, we can run the tests every time we create or alter the function. If you are doing TDD, you will start with listing 2 which has only the essential requirements, and expand the test once you have a function that passes all these basic tests. You need to keep adding edge cases to be absolutely sure that the function is robust.

Summary

Building this sort of test harness for each object would, at first glance, seem like a lot of extra work. It really isn’t because manual testing takes so much time that it is far better to create a good test harness before you get too far into the work of creating a procedure or function. SQL Prompt is wonderful for creating the data for this type of test harness through being able to generate those table-sources using multi-row VALUES statements.

Tools in this post

SQL Prompt

Write, format, and refactor SQL effortlessly

Find out more