23 January 2018
23 January 2018

How to Test SQL Server Functions and Procedures using SQL Prompt

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. 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.

These tests can take time to do properly, but there is a very handy feature in SQL Prompt that considerably lightens the workload. 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. 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 up the test harness 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…

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.


Specify grid output, execute the newly-fattened query, and then select the entire grid by clicking on the top left square.

We now right-click on the grid, and discover a SQL Prompt hidden treasure, Script as INSERT:

This feature converts this lot into a multi-row VALUES expression. After 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 ), – it looks like this:

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 in SQL Server Management Studio and Visual Studio.

Find out more

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.

Share this post.

Share on FacebookShare on Google+Share on LinkedInTweet about this on Twitter

You may also like

  • Article

    How we used your feedback to improve parentheses formatting in SQL Prompt 8.1

    After we released SQL Prompt 8, our priority was to continue to support the new formatting engine by fixing any bugs and reviewing feedback from users. One of the recurring patterns we noticed in your feedback regarded parentheses formatting. Some of you told us you couldn’t format the parentheses exactly the way you wanted to.

  • Article

    SQL Prompt to the rescue with tab coloring

    When you’re hard at work, it’s all too easy to make a mistake as you rush to get a job done. Say, for example, you have a QA database you need to get rid of. You run a query to drop it and then… oh no! You’ve accidentally run it in Production. Your day just

  • Article

    Building reusable table build scripts using SQL Prompt

    You’ve been working on a query, function or procedure and you want to store the results of executing it in a table; maybe a table variable, or a temporary table. These all require column definitions, and such things can be tiresome to do. Consider the following AdventureWorks query. SELECT * FROM Sales.Customer INNER JOIN Person.Person

  • Article

    Finding code smells using SQL Prompt: the SET NOCOUNT problem (PE008 and PE009)

    SQL Prompt implements two static code analysis rules to check code for potential misuse of the SET NOCOUNT command: PE008 – SET NOCOUNT OFF is used PE009 – No SET NOCOUNT ON before DML Whenever you execute a query, a short message is returned to the client with the number of rows that are affected

  • University

    Take the SQL Prompt course

    This Redgate University course takes you from installation all the way up to getting the most out of the advanced operations in SQL Prompt. As well as autocompleting your code, you’ll learn how SQL Prompt can help you with code formatting, object renaming, code analysis, and other useful tip and tricks.

  • Forums

    SQL Prompt Forum

    Write, format, and refactor SQL effortlessly