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

    Why your Development team needs SQL Prompt

    Alongside specialists, an IT department needs people who are broadly skilled and adaptable, who can pivot quickly to new projects, slot easily into new teams, and be productive quickly. SQL Prompt is the industry-leading SQL IntelliSense and code-formatting tool, and is an investment in developer versatility and productivity. It will both increase personal coding productivity

  • Article

    SQL Prompt Code Analysis: Table does not have clustered index (BP021)

    With a few exceptions, every table should have a clustered index. However, they are not always essential for performance. The value of a clustered index depends on the way a table is used, the typical pattern of queries, and how it the table is updated. More important for a table is that it should have

  • Article

    Finding code smells using SQL Prompt: TOP without ORDER BY in a SELECT statement (BP006)

    Using TOP in a SELECT statement without a subsequent ORDER BY clause is legal in SQL Server, but meaningless because asking for the TOP 10 rows implies that the data is guaranteed to be in a certain order, and tables have no implicit logical order. You must specify the order. In a SELECT statement, you

  • Article

    SQL Prompt Hidden Gems: The SSMS Results Pane

    Within SSMS, when executing a query, we can view the query results in a grid, or tabular, format (Ctrl-D), as plain text (Ctrl-T), or we can write them to a plain-text reporting (.rpt) file using Ctrl-Shift-F. However, over my 20 plus years as a SQL programmer, I’ve often needed to take these results and use

  • 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