IC Improve Code Recipes

Chapter 2

SQL Server Recipes That Hold Up

The database usually outlives the application. I have replaced Web Forms front ends, rewritten services, and moved code from .NET Framework 1.1 to .NET 8, and in most of those projects the stored procedures came along unchanged. My archive holds 68,998 hand-written SQL files from 32 engagements, with 24,750 stored procedures and 2,283 triggers among them. That is a lot of T-SQL that someone has to keep running.

Most of it was written in the style of SQL Server 2000, and it shows. Error handling still uses @@ERROR in about 992 files across 21 engagements, more than the 674 files in 12 engagements that use BEGIN TRY/BEGIN CATCH. Cursors appear in 24 of the 32 engagements. Paging with OFFSET ... FETCH, which has been in the product since SQL Server 2012, shows up in 5 files in one engagement. WITH (NOLOCK) appears in about 1,235 files in 17 engagements, usually added during a performance crisis and never removed.

None of these patterns is a disaster on its own. Together they make a database that is slow, hard to change and occasionally wrong. This chapter collects the T-SQL recipes I reach for when I take over one of these databases: a stored procedure template, paging, safe upserts, set-based replacements for cursors, dynamic search without injection, change auditing, and the truth about NOLOCK.

All listings target SQL Server 2019 or later unless a recipe says otherwise. They also run on Azure SQL Database. I use CREATE OR ALTER (SQL Server 2016 SP1 and later) so each script can be rerun.

Recipes

  1. 2.1A Stored Procedure TemplateA procedure that changes data needs to do four things right: validate its input, do its work in one transaction, roll back completely on any error,…
  2. 2.2Paging with OFFSET and FETCHA grid shows 25 customers per page out of 400,000. The application either loads all of them and pages in memory, or uses a paging query from the SQL…
  3. 2.3Upserts Done Safely"Insert the row, or update it if it already exists" is one of the most common requirements in business data. The obvious implementation has a race…
  4. 2.4Replacing Cursors with Set-Based SQLA nightly job applies late fees to overdue invoices. It loops through them with a cursor, one row at a time. It ran in two minutes when the company…
  5. 2.5Optional-Parameter Search with sp_executesqlA search screen has six optional filters. Either the procedure uses one static query full of @Param IS NULL OR conditions, which gets a single plan…
  6. 2.6Auditing Changes: Triggers vs Temporal TablesSomeone changed a customer's credit limit, and the business wants to know who, when and what it was before. The answer depends on an audit mechanism…
  7. 2.7Why NOLOCK Isn't a Performance FixReports block order entry, so someone adds WITH (NOLOCK) to the report queries. Then to the order screens. Then to everything. Blocking goes away,…

Chapter checklist

  • Start every procedure from the template: SET NOCOUNT ON, SET XACT_ABORT ON, validation, TRY/CATCH with THROW;.
  • Search for @@ERROR and convert those procedures as you touch them.
  • Replace ROW_NUMBER paging and in-memory paging with OFFSET ... FETCH and a unique tie-breaker, and use keyset paging for exports.
  • Rewrite check-then-insert upserts as update-then-insert with UPDLOCK, SERIALIZABLE, backed by a unique constraint.
  • List every cursor in the database and rewrite the ones in nightly jobs as set-based statements with OUTPUT.
  • Replace EXEC(@sql) with sp_executesql and typed parameters, and whitelist any identifier.
  • Check every trigger for single-row assumptions, and consider temporal tables for new history requirements.
  • Turn on read committed snapshot isolation, then remove NOLOCK hints starting with financial queries.