liveBook · Manning

Dynamic sql

As explained in 100 SQL Server Mistakes and How to Avoid Them

Dynamic SQL is SQL text constructed at runtime and then submitted for execution rather than being fixed in advance.

Dynamic SQL constructs query text at runtime. Concatenating login fields into that text may seem convenient, but it lets input alter the query's meaning and turns an authentication check into an attack surface. section 14.7

Mistake: concatenating login fields

A login query built from a username and password can be changed with input such as ' OR 1=1--, producing a query that returns a user without a valid password. More destructive payloads can create accounts, delete data, drop tables, or support lateral movement. section 14.7

Use these safer practices:

  • Prefer a stored procedure that accepts username and password variables instead of dynamically building the query. section 14.7
  • Enforce the stored-procedure standard at the application boundary; it protects against poor validation without rejecting legitimate names. section 14.7
Listing 14.19 Creating a login stored procedure
CREATE PROCEDURE dbo.Login
     @UserName NVARCHAR(128)
   , @Password NVARCHAR(128)
AS
BEGIN
   SELECT *
   FROM dbo.Users
   WHERE UserName = @UserName
       AND UserPassword = @Password ;
END

Inspect the parameterized login procedure and compare it with dynamically concatenated login SQL. section 14.7

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Explains query manipulation and consequences, then stops at stored-procedure enforcement rather than broader defensive implementation.
Examples
Uses a C# login page, concatenated SELECT statements, injection payloads, and a stored-procedure simulation.
What you can do after
Apply it safely by replacing dynamically built login SQL with a stored procedure receiving username and password variables.
How it connects
Connects dynamic SQL with SQL injection, stored procedures, input validation, authentication, and lateral movement.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.