IC Improve Code Recipes

Recipe 17.3 · C#

One Transaction for a Multi-Table Insert Procedure

Problem

Saving an incident in CFATS Manager touches several tables: the incident row, a row linking the incident to its facility, and a person row for "reported to" (found or created by name). The work is spread across a chain of procedures, and none of them uses a transaction. If any step fails after the first insert, you get an orphaned incident that belongs to no facility and never appears on any screen.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

From CFATS Manager, re-wrapped. The USE line is removed and the parameter names are as they were.

SQL
-- From CFATS Manager: CFATSDatabase\StoredProcedure\
-- dbo.InsertFacilityIncidentDefault.StoredProcedure.sql
-- (re-wrapped, abridged)
CREATE PROCEDURE [dbo].[InsertFacilityIncidentDefault]
    @IncidentID int output, @FacilityID int,
    @II_rblIncidentTypeNo int, @II_txtIncidentName varchar(100),
    @II_txtOccurenceDate datetime, @II_txtLocation varchar(200),
    @II_txtReportedTo varchar(200),
    @II_txtDescription varchar (500),
    @II_txtResponse varchar(500),
    @II_propFileGUID uniqueidentifier
AS
BEGIN
    -- Usage: Called from IncidentInput.aspx, abbreviation
    -- prefix is II for page controls
    -- Format: PageName_ControlName_Function
    SET NOCOUNT ON
    SET ANSI_NULLS ON
    DECLARE @Result int,@Nothing int

    EXECUTE @Result = InsertIncidentDefault @IncidentID OUTPUT,
        @II_rblIncidentTypeNo, @II_txtIncidentName,
        -- ...
        @II_propFileGUID

    INSERT INTO tblFacilityIncident(FacilityID,IncidentID)
        VALUES(@FacilityID,@IncidentID)
END

InsertIncidentDefault in turn calls InsertIncidentBasic to insert the row, FindPersonID to find or create the person, and then runs an UPDATE to fill in the remaining columns. That's four procedures and four separate commits for one save. The parameter names carry the page prefix and the control type (II_txt, II_rbl), which ties the database to one ASP.NET form. The threat and near-miss forms have their own copies with TI_ and other prefixes.

The improved recipe

T-SQL for SQL Server 2016 or later (CREATE OR ALTER needs 2016 SP1).

SQL
CREATE OR ALTER PROCEDURE dbo.Incident_Insert
    @FacilityID     int,
    @IncidentTypeNo int,
    @Name           varchar(100),
    @OccurredAt     datetime2(0),
    @Location       varchar(200) = NULL,
    @ReportedTo     varchar(200) = NULL,
    @Description    varchar(500) = NULL,
    @Response       varchar(500) = NULL,
    @FileGUID       uniqueidentifier = NULL,
    @IncidentID     int OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    DECLARE @ReportedToPersonID int = NULL;

    BEGIN TRY
        BEGIN TRANSACTION;

        IF @ReportedTo IS NOT NULL
            EXEC dbo.FindPersonID
                 @PersonID   = @ReportedToPersonID OUTPUT,
                 @Name       = @ReportedTo,
                 @PersonType = 'IncidentReportedTo';

        INSERT INTO dbo.tblIncident
            (IncidentTypeNo, Name, OccurenceDate, Location,
             ReportedToPersonID, Description, Response, FileGUID)
        VALUES
            (@IncidentTypeNo, @Name, @OccurredAt, @Location,
             @ReportedToPersonID, @Description, @Response, @FileGUID);

        SET @IncidentID = SCOPE_IDENTITY();

        INSERT INTO dbo.tblFacilityIncident (FacilityID, IncidentID)
        VALUES (@FacilityID, @IncidentID);

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        THROW;
    END CATCH;
END;

The C# side implements IIncidentStore from Recipe 17.2. Packages: Microsoft.Data.SqlClient.

C#
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using ImproveCode.Cfats.Data;
using ImproveCode.Cfats.Incidents;
using Microsoft.Data.SqlClient;

namespace ImproveCode.Cfats.Data.Sql;

public sealed class SqlIncidentStore(
    ISqlConnectionFactory db, IIncidentTypeLookup types)
    : IIncidentStore
{
    public async Task<int> InsertAsync(
        NewIncident i, CancellationToken ct)
    {
        await using SqlConnection conn = db.Create();
        await using SqlCommand cmd = new("dbo.Incident_Insert", conn)
        {
            CommandType = CommandType.StoredProcedure
        };

        SqlParameterCollection p = cmd.Parameters;
        p.Add("@FacilityID", SqlDbType.Int).Value = i.FacilityId;
        p.Add("@IncidentTypeNo", SqlDbType.Int).Value =
            types.GetTypeNo(i.Kind);
        p.Add("@Name", SqlDbType.VarChar, 100).Value = i.Name;
        p.Add("@OccurredAt", SqlDbType.DateTime2).Value =
            i.OccurredAt.UtcDateTime;
        p.Add("@Location", SqlDbType.VarChar, 200).Value =
            DbValue(i.Location);
        p.Add("@ReportedTo", SqlDbType.VarChar, 200).Value =
            DbValue(i.ReportedTo);
        p.Add("@Description", SqlDbType.VarChar, 500).Value =
            DbValue(i.Description);
        p.Add("@Response", SqlDbType.VarChar, 500).Value =
            DbValue(i.Response);
        p.Add("@FileGUID", SqlDbType.UniqueIdentifier).Value =
            i.FileId is Guid g ? g : DBNull.Value;

        SqlParameter id = p.Add("@IncidentID", SqlDbType.Int);
        id.Direction = ParameterDirection.Output;

        await conn.OpenAsync(ct);
        await cmd.ExecuteNonQueryAsync(ct);
        return (int)id.Value;
    }

    private static object DbValue(string? s) =>
        string.IsNullOrWhiteSpace(s) ? DBNull.Value : s;
}

public interface IIncidentTypeLookup
{
    int GetTypeNo(IncidentKind kind);
}

How it works

BEGIN TRANSACTION wraps the person lookup and both inserts, so they commit together or not at all. FindPersonID runs inside the same transaction. If the facility link fails, the person it just created is rolled back too. I tested exactly that case against LocalDB by forcing a primary-key violation on the link table: the incident and person counts were unchanged afterwards.

SET XACT_ABORT ON makes any run-time error doom the transaction, including a client timeout that never reaches the CATCH block. THROW with no arguments re-raises the original error number and message, so the C# caller gets a real SqlException instead of a return code nobody checked.

Parameter names describe data, not controls. The same procedure now serves the incident form, a future API and a bulk import. datetime2(0) replaces datetime, and the C# side sends UTC.

The insert happens in one statement instead of an insert followed by an update, so no reader ever sees a half-filled row.

Variations and pitfalls

  • Threats and near misses. Add @CommunicatedBy and @IdentifiedBy as optional parameters with two more FindPersonID calls, and delete the per-form copies.
  • FindPersonID is simplified here. The product's version takes six positional parameters, including flags that control usage counts. Call any helper procedure with named parameters, as above, so a signature change fails loudly.
  • Find-or-create by name is a race. Two saves naming the same new person at once can create two rows. Add a unique index on the natural key and catch error 2627 in the helper, or use MERGE with HOLDLOCK (Chapter 2).
  • Scripts with USE [DevDatabase] at the top. Every script in the old database project starts with USE and the development database's name, because they were generated from Management Studio. Deploying one to production runs it against the wrong database or fails. Strip USE lines and let the deployment tool pick the database.