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.
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.
"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."
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
| # | 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 |
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.
NOCOUNT and UTC dates (6).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.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.
Checks whether the candidate can review T-SQL for security, correctness and performance and rank findings by impact.
Green flags
Red flags
@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.
.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.
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.
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.
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.
Batch jobs get retried. A guard column (LateFeeAppliedOn) or a unique constraint on (InvoiceId, FeeDate) makes a rerun harmless.
@Region in a scratch database and watch the extra statement execute.WAITFOR DELAY, then query sys.dm_tran_session_transactions to see the orphaned transaction.SET STATISTICS IO, TIME ON.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
}
}
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.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.ROLLBACK if XACT_STATE() <> 0, then THROW.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.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.
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.
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.
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.
Last updated 23 Nov 2026.