Skip to content

Instantly share code, notes, and snippets.

@aev-mambro2
Last active February 4, 2021 20:38
Show Gist options
  • Save aev-mambro2/787ec65d6cbe12f1aa9a69e3d83bbd8f to your computer and use it in GitHub Desktop.
Save aev-mambro2/787ec65d6cbe12f1aa9a69e3d83bbd8f to your computer and use it in GitHub Desktop.
Use Common Table Expressions when Unit Testing in TSQL
Use Common Table Expressions when Unit Testing in TSQL
TSQL, Microsoft's SQL dialect for SQLServer, is capable of executing CTE, also known as Common Table Expression.
We can use these to separate concerns when setting up unit tests, like so, to determine whether a new process
returns the same records as an old process:
WITH old_batch (found) as (SELECT FIELD AS found FROM OLD_QUERY_OR_PROCESS),
new_batch (found) as (SELECT FIELD AS found FROM NEW_QUERY_OR_PROCESS),
compare_old_to_new (found) as (select found from old_batch where found not in (select found from new_batch)),
compare_new_to_old (found) as (select found from new_batch where found not in (select found from old_batch)),
count_compare_1 (amount) as (select count(*) from compare_old_to_new),
count_compare_2 (amount) as (select count(*) from compare_new_to_old),
test_1 (result) as (select iif(0=amount,1,0) from count_compare_1),
test_2 (result) as (select iif(0=amount,1,0) from count_compare_2),
interpret_results (interpretation) as (select iif(
(1=(select result from test_1))
and (1=(select result from test_2))
),1,0)
),
verdict (verdict) as (select iif(1=interpretation,'True','False') from interpret_results)
select verdict from verdict;
This makes the individual steps very visible and easy to read.
Happy coding!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment