VBA to T-SQL via TDD: Step 8

Step 8. Alter the scalar function to address failures

VBA to T-SQL via TDD: Step 8

This is Part 1 of my series on converting a VBA function to a SQL Server scalar function using test driven development.  As a proof of concept, I will be re-implementing the VBA Round function (which uses bankers rounding) as a SQL Server scalar function.

The key to test-driven development is to start with enough tests to cover every anticipated scenario.

If you do that, then the rest is easy.  

  1. Review the failed tests
  2. Write code to address the failures
  3. Re-run the tests
  4. If all tests pass, you're done; otherwise, return to step 1

Banker's Rounding Example

In Step 7, we ran our test query to verify that all the tests fail when running against a dummy function that is hard-coded to always return zero.  The test query returned 17 rows.  In other words, 17 of our 19 test cases failed....which means that two test cases passed even with the dummy function!

Here's our table of test data. It turns out that a dummy function that always returns zero can pass some tests. As my high school basketball coach used to say, "Even a blind squirrel finds an acorn once in awhile."

Addressing the failing tests

Let's start by updating the scalar function to use SQL Server's built-in rounding function.  If I didn't already know better, it would be reasonable to believe that using the Round function in T-SQL would generate identical results to the Round function in VBA.

ALTER FUNCTION [dbo].[VBA_Round](
    @OriginalVal sql_variant,
    @RoundDigits int
)
RETURNS float
AS
BEGIN
    RETURN Round(Cast(@OriginalVal as float), @RoundDigits)
END;
WARNING! This is a work-in-progress. It is NOT a working prototype for a T-SQL banker's rounding function. (But we will get there.)

Referenced articles

How to Convert a VBA Function to a SQL Server Scalar Function
MS Access Developers Can Remove All the Risk From This Complex Process With These 3 Words
Trust But Verify
What Ronald Reagan’s Words Can Teach Us About the Sample Code We Find on the Internet
VBA to T-SQL via TDD: Step 7
Step 7. Execute the test query in SQL Server to verify it fails
VBA to T-SQL via TDD: Step 6
Step 6. Build a test query in SQL Server to return failing tests
VBA to T-SQL via TDD: Step 5
Step 5. Create a dummy scalar function in SQL Server

All original code samples by Mike Wolfe are licensed under CC BY 4.0