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

Related posts

Also in Hub

Misuse of the scalar user-defined function as a constant (PE017)

Do not use a scalar user-defined function (UDF) in a JOIN condition, WHERE search condition, or in a SELECT list, unless the function is schema-bound. Scalar UDFs are often used without a parameter to...

Also in Product learning

Customizing the SQL Prompt built-in snippets: a better 'ata' snippet

Snippets are a great feature of SQL Prompt. They save coding time, and introduce standards and consistency to the way you build code modules. They have multiple replacement points (placeholders) for p...

Also in SQL Prompt

Avoid T-SQL Technical Debt using SQL Prompt Code Analysis

SQL Prompt's Code Analysis feature helps you discover code issues and hidden pitfalls during code development, as you type. It also provides tips for improving your code, and includes links to documen...

Also about SQL Prompt

How you can improve your SQL with code analysis in SQL Prompt

What is code analysis?

Code analysis is a formal automated process of scanning a piece of software code and deducing potential problems, issues and faults that may not be apparent to programmers at f...