Lesson 1 of 2 Stored Procedures and Triggers

Writing Secure and Efficient Stored Procedures

This lesson explains procedure parameters, table-valued parameters, safe dynamic SQL, parameter sniffing and how procedures support least privilege.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish between OUTPUT parameters, return codes and result sets.
  • Explain how sp_executesql prevents SQL injection in dynamic SQL.
  • Describe parameter sniffing and its remedies.

Parameters and results

A procedure declares input parameters with optional defaults and OUTPUT parameters that return values to the caller. It can return any number of result sets and an integer return code with RETURN, which conventionally signals status (0 for success), not data. Table-valued parameters (TVPs) pass a set of rows in one call: they are declared with a user-defined table type and must be READONLY. A JSON parameter parsed with OPENJSON is an alternative that clients without TVP support can use.

CREATE TYPE Sales.OrderLineType AS TABLE (ProductID int NOT NULL, Quantity smallint NOT NULL);
GO
CREATE OR ALTER PROCEDURE Sales.usp_CreateOrder
    @CustomerID int,
    @Lines      Sales.OrderLineType READONLY,
    @OrderID    int OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    BEGIN TRANSACTION;
        INSERT INTO Sales.Orders (CustomerID, OrderDate, Status)
        VALUES (@CustomerID, SYSUTCDATETIME(), 'Open');
        SET @OrderID = SCOPE_IDENTITY();
        INSERT INTO Sales.OrderLines (OrderID, LineNumber, ProductID, Quantity)
        SELECT @OrderID, ROW_NUMBER() OVER (ORDER BY ProductID), ProductID, Quantity FROM @Lines;
    COMMIT;
END;
Match the pairs

Procedure outputs

Exam skills 1.2.4

Match each way a procedure communicates with its purpose.

Log in to try this activity Interactive activities are free with an account.

Dynamic SQL and injection

Search procedures sometimes build SQL at run time, for example to add optional filters. Concatenating user input into a string executed with EXEC(@sql) allows SQL injection. sp_executesql with a parameter list keeps values as parameters and lets plans be reused; object names that must be dynamic are validated against metadata and wrapped with QUOTENAME. Dynamic SQL runs in its own scope, so ownership chaining does not apply and the caller needs permissions on the referenced objects, unless the procedure uses EXECUTE AS or is signed with a certificate.

DECLARE @sql nvarchar(max) = N'SELECT ProductID, Name FROM Catalog.Product WHERE 1 = 1';
IF @Category IS NOT NULL SET @sql += N' AND CategoryID = @cat';
IF @MaxPrice IS NOT NULL SET @sql += N' AND ListPrice <= @max';
EXEC sp_executesql @sql, N'@cat int, @max decimal(10,2)', @cat = @Category, @max = @MaxPrice;
Spot the bug

A search procedure open to injection

Exam skills 1.2.4

Find the lines that allow SQL injection.

Log in to try this activity Interactive activities are free with an account.

Plans, parameter sniffing and security

A procedure's plan is compiled for the parameter values of its first execution and reused. When values differ greatly in selectivity, for example a customer with ten orders and one with ten million, the reused plan can be poor (parameter sniffing). Remedies include OPTION (RECOMPILE) on the statement, OPTIMIZE FOR, Query Store hints, and parameter sensitive plan optimization in compatibility level 160 and later, which caches several plans per query.

For security, granting EXECUTE on procedures (or on a schema) without table permissions makes procedures the only path to data, because ownership chaining skips permission checks on objects with the same owner. SET NOCOUNT ON suppresses "rows affected" messages, which reduces network traffic, and SET XACT_ABORT ON makes errors roll back the whole transaction.

Scenario questions

Sniffing and security

Exam skills 1.2.4 · 2.2.4

Choose the remedy for each situation.

Log in to try this activity Interactive activities are free with an account.
Worked example

Bulk order submission

A mobile app submits an order with up to 50 lines. Today it calls a procedure once per line, which takes 50 round trips and sometimes leaves partial orders when the connection drops. The order ID must be returned to the app. What should the developer change?

Create a procedure that accepts the lines as a table-valued parameter (or a JSON parameter shredded with OPENJSON), inserts the header and all lines in one transaction with SET XACT_ABORT ON, and returns the new order ID in an OUTPUT parameter. One call removes the round trips, and the transaction ensures that either the whole order or nothing is saved. Returning the ID with RETURN would misuse the status code, which is limited to an integer status.

Check yourself

How must a table-valued parameter be declared in a procedure?

Show answer

With a user-defined table type and the READONLY keyword.

Exam Tips

Remember for the exam

  • Many rows in one call: a table-valued parameter (READONLY) or JSON with OPENJSON.
  • Return data values: OUTPUT parameters; RETURN is for a status code.
  • Dynamic SQL: sp_executesql with parameters; QUOTENAME for identifiers.
  • Parameter sniffing: RECOMPILE, OPTIMIZE FOR, Query Store hints or PSP optimization.