📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: a colleague's stored procedure loops over orders with a cursor, builds a dynamic SQL filter by concatenating a parameter, uses SELECT * with NOLOCK on every table, and has no SET XACT_ABORT ON or error handling around its transaction. What would you flag, in what order, and how would you rewrite it?

Reviewing a T-SQL stored procedure: SQL injection through concatenated dynamic SQL, transaction handling without XACT_ABORT, NOLOCK data errors, row-by-row cursors, SELECT * and how to rewrite it set-based and safely.

Senior CodeReview Advanced code-review sql-injection sql-server stored-procedures t-sql transactions

🎯 Key points

  • Concatenated dynamic SQL is SQL injection: use static SQL or sp_executesql with parameters; validate dynamic identifiers against an allow-list and wrap them in QUOTENAME
  • No XACT_ABORT: a timeout or client cancel leaves an open transaction holding locks on a pooled connection
  • TRY...CATCH with XACT_STATE() check, ROLLBACK and THROW so the caller (and its logging and alerts) sees the error
  • NOLOCK reads uncommitted data and can miss or duplicate rows, so billed amounts and reports are wrong; use RCSI instead
  • Cursor processes row by row: rewrite as one set-based UPDATE/INSERT, batch if large
  • Batch jobs get retried after timeouts: make them idempotent (guard column or unique constraint) to avoid double charges
  • SELECT * breaks on schema changes and defeats covering indexes
  • Rank findings: security and stuck locks first, then wrong data, then performance, then style

⏱ 30-second answer

I'd rank by impact. First, SQL injection: concatenating a parameter into dynamic SQL lets a caller run anything; use sp_executesql with parameters and QUOTENAME for identifiers. Second, transaction safety: without SET XACT_ABORT ON, a command timeout or client cancel can leave the transaction open on a pooled connection, holding locks until someone kills it; add TRY...CATCH with XACT_STATE(), ROLLBACK and THROW. Third, wrong data: NOLOCK can return uncommitted, missing or duplicated rows; use RCSI for non-blocking reads. Fourth, performance: the cursor does row-by-row work that one set-based statement can do; SELECT * breaks covering indexes and schema changes.

The rewrite is shorter, safer and typically orders of magnitude faster.

🗣 Full answer (senior)

How I would answer this in an interview

"I review in order of blast radius: security holes and things that can stall the system first, then anything that returns or writes wrong data, then performance, then style.

The dynamic SQL is the first blocker. It appends @Region straight into the string, so a value like x'; DROP TABLE dbo.Orders;-- runs as written under the procedure's permissions. Procedures aren't automatically safe; only parameters are. I'd rewrite it with sp_executesql and a typed parameter, and if a column or table name really has to be dynamic, validate it against an allow-list and wrap it in QUOTENAME.

Second blocker: the transaction. There's BEGIN TRAN ... COMMIT with no XACT_ABORT and no TRY/CATCH. If the .NET command times out, the client sends an attention signal, the batch stops, and the transaction stays open. The connection goes back to the pool still holding locks, and everything touching those rows blocks. For example, at [company] we [had a month-end job that timed out and left an open transaction blocking order processing for 25 minutes until a DBA killed the session]. XACT_ABORT ON makes SQL Server roll back on timeout and most errors, and TRY/CATCH with THROW surfaces the error properly.

Third, NOLOCK everywhere. It's read uncommitted: dirty reads of rows that get rolled back, and during page splits it can skip rows or read them twice. For an invoicing procedure that's wrong totals. If the goal is avoiding blocking, read committed snapshot does that correctly.

Then performance: the cursor fetches each order and updates it one at a time, which is 50,000 round trips inside the engine; a single UPDATE with a join does it in one pass. And SELECT * means extra I/O, no covering indexes, and broken INSERT ... SELECT when someone adds a column.

I'd mark the first three as blocking comments, the rest as strong suggestions, and add a checklist item and a static analysis rule so we catch it next time."


Code under review

CREATE PROCEDURE dbo.ApplyLateFees @Region varchar(50), @FeePct decimal(5,2)
AS
BEGIN
    BEGIN TRAN;                                                    -- 2: no XACT_ABORT, no TRY/CATCH

    DECLARE @sql nvarchar(max) =
        N'SELECT * FROM dbo.Invoices WITH (NOLOCK) WHERE Region = ''' + @Region + N''''; -- 1: injection; 3: NOLOCK; 5: SELECT *

    CREATE TABLE #Late (InvoiceId int, CustomerId int, Region varchar(50), Amount decimal(19,4),
                        DueDate date, PaidDate date, Status varchar(20));
    INSERT #Late EXEC (@sql);                                      -- breaks if Invoices gains a column

    DECLARE @id int, @amount decimal(19,4);
    DECLARE c CURSOR FOR SELECT InvoiceId, Amount FROM #Late WHERE DueDate < GETDATE() AND PaidDate IS NULL; -- 4: cursor
    OPEN c;
    FETCH NEXT FROM c INTO @id, @amount;
    WHILE @@FETCH_STATUS = 0
    BEGIN
        UPDATE dbo.Invoices SET Amount = @amount * (1 + @FeePct / 100) WHERE InvoiceId = @id;
        INSERT dbo.InvoiceFees (InvoiceId, Fee) VALUES (@id, @amount * @FeePct / 100);
        FETCH NEXT FROM c INTO @id, @amount;
    END
    CLOSE c; DEALLOCATE c;

    COMMIT;
END

Findings, by severity

# Severity Finding Fix
1 Security (blocking) @Region concatenated into dynamic SQL: injection Static SQL here; otherwise sp_executesql with parameters, QUOTENAME for identifiers
2 Stall (blocking) Transaction without XACT_ABORT or TRY/CATCH: timeout leaves open transaction and locks SET XACT_ABORT ON, TRY/CATCH, XACT_STATE(), THROW
3 Wrong data (blocking) NOLOCK on the data being billed: dirty, missing or duplicate rows Remove; use RCSI for non-blocking reads; lock rows being updated
4 Wrong data / performance Cursor re-reads stale #Late amounts, row-by-row updates; running twice double-charges One set-based UPDATE with OUTPUT into the fees table, idempotency guard
5 Maintainability SELECT * into a fixed temp table Explicit columns
6 Diagnostics No SET NOCOUNT ON, GETDATE() local time SET NOCOUNT ON, SYSUTCDATETIME() or a date parameter

The rewrite

See the code example: static, parameterised SQL; one set-based UPDATE with OUTPUT into InvoiceFees; a LateFeeAppliedOn guard so a rerun doesn't double-charge; XACT_ABORT with TRY/CATCH; no NOLOCK.

How I'd close the review

  • Blocking: 1, 2, 3 and the double-charge risk in 4.
  • Suggested: set-based rewrite (4), explicit columns (5), NOCOUNT and UTC dates (6).
  • Process: add SQL code analysis rules in the SQL project (e.g. SR0001 for SELECT *, and a rule or review check for EXEC(@sql) and NOLOCK), a procedure template with XACT_ABORT and TRY/CATCH, and a checklist item for idempotency of batch jobs.

Production example

The rewritten procedure processed 48,000 late invoices in 1.4 seconds instead of 6 minutes 20 seconds, held locks for about 1 second instead of 6 minutes, and a rerun on the same day changed zero rows.

🔍 What the interviewer is checking

Checks whether the candidate can review T-SQL for security, correctness and performance and rank findings by impact.

Green flags

  • Flags the injection first and fixes it with sp_executesql and QUOTENAME
  • Explains the orphaned transaction risk and XACT_ABORT
  • Knows NOLOCK's dirty, missing and duplicate row problems and suggests RCSI
  • Rewrites the cursor set-based and adds idempotency
  • Proposes a process fix (analysis rules, template, checklist)

Red flags

  • Starts with formatting or SELECT *
  • Thinks procedures are immune to injection
  • Keeps NOLOCK as a performance tip

📚 Learn in depth

1. How injection works through dynamic SQL

@Region = N'NSW'' ; DELETE dbo.Invoices; --'

'SELECT * FROM dbo.Invoices WHERE Region = ''' + @Region + ''''
  -> SELECT * FROM dbo.Invoices WHERE Region = 'NSW' ; DELETE dbo.Invoices; --'

EXEC(@sql) runs whatever the string contains. sp_executesql @sql, N'@Region varchar(50)', @Region sends the value as data, never as code, and also reuses one cached plan. Identifiers can't be parameters, so validate them against sys.columns or an allow-list and use QUOTENAME.

2. What happens on a timeout without XACT_ABORT

.NET SqlCommand (CommandTimeout = 30s)
   |-- BEGIN TRAN; UPDATE ... (row locks taken)
   |-- 30s elapsed -> client sends Attention
   |-- server stops the batch, transaction REMAINS OPEN
   |-- connection returned to pool (still in transaction)
   v
Other sessions block on those locks; next user of the pooled connection
may even run inside the orphaned transaction until reset.

SET XACT_ABORT ON makes the server roll back the transaction when the attention arrives and on most run-time errors. Connection reset on reuse (sp_reset_connection) also rolls back, but only when the connection is reused, which may be minutes later.

3. The TRY/CATCH pattern

SET XACT_ABORT, NOCOUNT ON;
BEGIN TRY
  BEGIN TRAN; ... COMMIT;
END TRY
BEGIN CATCH
  IF XACT_STATE() <> 0 ROLLBACK;
  THROW;   -- re-raise the original error to the caller
END CATCH

XACT_STATE() is -1 for an uncommittable transaction, 1 for active, 0 for none.

4. NOLOCK's real behaviour

Read uncommitted takes no shared locks and uses allocation-order scans, so it can read rows that are later rolled back, miss rows moved by a page split, or read them twice. RCSI gives readers the last committed version from the version store, without blocking writers.

5. Cursors versus set-based

Each cursor iteration is a separate statement execution with its own locks and log records. The set-based version is one statement, one plan, minimal logging overhead. For millions of rows, batch it (UPDATE TOP (5000) in a loop on an indexed predicate) to keep log and lock escalation under control.

6. Idempotency

Batch jobs get retried. A guard column (LateFeeAppliedOn) or a unique constraint on (InvoiceId, FeeDate) makes a rerun harmless.

Try it yourself

  1. Run the original procedure with a malicious @Region in a scratch database and watch the extra statement execute.
  2. Start the original from .NET with a 1-second timeout and a WAITFOR DELAY, then query sys.dm_tran_session_transactions to see the orphaned transaction.
  3. Compare the cursor and set-based versions on 50,000 invoices with SET STATISTICS IO, TIME ON.
  4. Enable RCSI on a test database and confirm readers no longer block on writers without NOLOCK.

💻 Code

The rewritten procedure: static parameterised SQL, set-based, idempotent and transaction-safe.

CREATE OR ALTER PROCEDURE dbo.ApplyLateFees
    @Region varchar(50),
    @FeePct decimal(5,2),
    @AsOf   date
AS
BEGIN
    SET NOCOUNT, XACT_ABORT ON; -- roll back on timeout/cancel and most errors

    IF @FeePct <= 0 OR @FeePct > 20
        THROW 50010, N'FeePct must be between 0 and 20.', 1;

    BEGIN TRY
        BEGIN TRANSACTION;

        -- One set-based statement; OUTPUT writes the fee rows from the same change
        UPDATE i
        SET i.Amount = i.Amount * (1 + @FeePct / 100),
            i.LateFeeAppliedOn = @AsOf               -- idempotency guard
        OUTPUT inserted.InvoiceId,
               deleted.Amount * @FeePct / 100,
               @AsOf
        INTO dbo.InvoiceFees (InvoiceId, Fee, FeeDate)
        FROM dbo.Invoices AS i
        WHERE i.Region = @Region                      -- parameter, not concatenation
          AND i.DueDate < @AsOf
          AND i.PaidDate IS NULL
          AND i.LateFeeAppliedOn IS NULL;             -- rerun changes nothing

        COMMIT;
    END TRY
    BEGIN CATCH
        IF XACT_STATE() <> 0 ROLLBACK;
        THROW; -- surface the original error to the caller
    END CATCH
END;
GO

-- Supporting index for the predicate
CREATE INDEX IX_Invoices_LateFees
    ON dbo.Invoices (Region, DueDate)
    INCLUDE (Amount)
    WHERE PaidDate IS NULL AND LateFeeAppliedOn IS NULL;

-- If dynamic SQL is truly needed (e.g. a user-chosen sort column):
DECLARE @SortColumn sysname = N'DueDate';
IF @SortColumn NOT IN (N'DueDate', N'Amount', N'InvoiceId')
    THROW 50011, N'Invalid sort column.', 1;
DECLARE @sql nvarchar(max) = N'SELECT InvoiceId, Amount, DueDate FROM dbo.Invoices WHERE Region = @Region ORDER BY '
    + QUOTENAME(@SortColumn) + N';';
EXEC sys.sp_executesql @sql, N'@Region varchar(50)', @Region = N'NSW';
using System.Data;
using Microsoft.Data.SqlClient;

namespace Billing.Jobs;

public sealed class LateFeeJob(string connectionString, TimeProvider clock)
{
    public async Task RunAsync(string region, decimal feePct, CancellationToken ct)
    {
        await using var conn = new SqlConnection(connectionString);
        await conn.OpenAsync(ct);
        await using var cmd = new SqlCommand("dbo.ApplyLateFees", conn)
        {
            CommandType = CommandType.StoredProcedure,
            CommandTimeout = 120
        };
        cmd.Parameters.Add("@Region", SqlDbType.VarChar, 50).Value = region;
        cmd.Parameters.Add("@FeePct", SqlDbType.Decimal).Value = feePct;
        cmd.Parameters["@FeePct"].Precision = 5;
        cmd.Parameters["@FeePct"].Scale = 2;
        cmd.Parameters.Add("@AsOf", SqlDbType.Date).Value = DateOnly.FromDateTime(clock.GetUtcNow().UtcDateTime);
        await cmd.ExecuteNonQueryAsync(ct); // safe to retry: the procedure is idempotent
    }
}

⚠ Common mistakes

  • Mistake: Believing stored procedures prevent SQL injection by themselves. Why it is wrong: EXEC(@sql) with concatenated input is as injectable as concatenated SQL in C#. Instead: Static SQL, or sp_executesql with parameters and QUOTENAME for identifiers.
  • Mistake: Transactions without SET XACT_ABORT ON. Why it is wrong: A client timeout leaves the transaction open on a pooled connection, holding locks. Instead: Always SET XACT_ABORT ON in procedures that open transactions.
  • Mistake: Catching errors and not re-raising. Why it is wrong: The caller thinks the call succeeded. Instead: ROLLBACK if XACT_STATE() <> 0, then THROW.
  • Mistake: Adding NOLOCK to fix blocking. Why it is wrong: It trades blocking for dirty, missing and duplicate rows. Instead: Enable RCSI and fix the queries that hold locks too long.
  • Mistake: Cursors for set-based work. Why it is wrong: Row-by-row execution holds locks longer and is far slower. Instead: One set-based statement, batched if large.
  • Mistake: Batch jobs that aren't idempotent. Why it is wrong: A retry after a timeout charges customers twice. Instead: A guard column or unique constraint so reruns change nothing.
  • Mistake: Reviewing style first. Why it is wrong: The reviewer runs out of attention before the injection and transaction bugs. Instead: Rank by severity: security and stalls, wrong data, performance, style.

🏛 Senior insight: trade-offs

What makes this senior is the ordering and the process fix. Anyone can spot a cursor; the injection and the orphaned transaction are what cause incidents, and the double-charge on retry is what causes a customer complaint and a regulator's letter. I'd also ask why the code got this far: a procedure template, SQL code analysis in the build, and a short checklist prevent the next one.

Finding Blocking? Why
Concatenated dynamic SQL Yes Security: arbitrary SQL under the procedure's rights
No XACT_ABORT / TRY-CATCH Yes Orphaned transactions and blocking
NOLOCK on billed data Yes Wrong amounts
Not idempotent Yes Double charges on retry
Cursor Strong suggestion Performance and lock duration
SELECT *, NOCOUNT, GETDATE Suggestion Maintainability and correctness of dates

Measure the improvement with SET STATISTICS IO, TIME ON, lock duration via sys.dm_tran_locks during the run, and Query Store duration before and after.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions injection through dynamic SQL Why: Checks the same injection risk on the EF Core side (FromSqlRaw vs FromSql).
    How to answer

    Use raw SQL for what LINQ can't express well: hints, window functions, full-text search, table-valued functions or stored procedures. FromSql($"... {id}") takes a FormattableString, so every interpolation hole becomes a DbParameter; that is the safe default. FromSqlRaw takes a plain string and is safe only with explicit @p parameters: passing $"...{input}" to it concatenates the value into SQL, which is SQL injection (EF Core 8's EF1002 analyser warns about it). SqlQuery<T> returns scalars or unmapped DTOs, and ExecuteSql runs commands. Identifiers such as sort columns can never be parameters, so whitelist them. A composable SELECT can have LINQ added on top (EF wraps it as a subquery), but EXEC cannot. The trade-off is power and performance versus losing compile-time checking, so keep raw SQL small and tested.

  2. When: Candidate flags NOLOCK Why: Checks precise understanding of read uncommitted anomalies and RCSI.
    How to answer

    NOLOCK is read uncommitted: it reads rows other transactions haven't committed (which may be rolled back), and because it can use allocation-order scans without shared locks, it can skip rows or read them twice when pages split during the scan. It can even fail with error 601. It removes blocking by giving up correctness. Use read committed snapshot isolation (RCSI), the default in Azure SQL Database, so readers see the last committed version without blocking writers, and fix the long write transactions that cause blocking.

🛠 Real-world problems: how you handle them

Late-fee procedure timeout leaves an open transaction and double charges
Situation
A [billing] system ran a nightly late-fee stored procedure from a .NET worker against Azure SQL, about [50,000] invoices per region. The procedure used a cursor, NOLOCK and dynamic SQL, with no XACT_ABORT.
Signals
One night the worker logged a command timeout and retried. By morning order processing was blocked: Application Insights showed SQL dependency timeouts, and customers in one region later complained about two late fees on the same invoice.
Investigation
Used sp_WhoIsActive to find a sleeping session with an open transaction (open_tran_count = 1) at the head of the blocking chain; sys.dm_tran_session_transactions confirmed it had been open for over 20 minutes. Read the procedure and found no XACT_ABORT. Queried InvoiceFees and found duplicate fee rows from the retry.
Resolution
Killed the orphaned session, refunded duplicate fees, then rewrote the procedure: static parameterised SQL, one set-based UPDATE with OUTPUT into InvoiceFees, a LateFeeAppliedOn guard, XACT_ABORT with TRY/CATCH and THROW, and no NOLOCK.
Prevention
Added a procedure template with XACT_ABORT and TRY/CATCH, SQL code analysis rules in the SQL project build, an alert on transactions open longer than 60 seconds, and an integration test that runs the job twice and asserts one fee per invoice.

How to tell it (STAR)

**S:** At [company], a nightly late-fee job timed out, blocked order processing for about [25 minutes], and its retry double-charged some customers. **T:** I was asked to fix the incident and make sure it couldn't recur. **A:** I found an orphaned transaction from the timed-out call, because the procedure had no XACT_ABORT. In the review I ranked the issues: injection in the dynamic SQL, the transaction handling, NOLOCK on billed data and the lack of idempotency, then the cursor. I rewrote it set-based with a guard column and proper error handling and added a template and analysis rules. **R:** The job went from about [6 minutes] to [1.4 seconds], reruns now change zero rows, and we haven't had an orphaned transaction from it since.

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me