Database programming
Stored procedures and parameters
Define a boundary for repeatable data operations.
Understand the concept
A procedure is a database program with input parameters and potentially several operations. Result sets, OUTPUT parameters and RETURN status codes are different output channels. SET NOCOUNT ON suppresses row-count messages, not results.
For atomic operations, design XACT_ABORT, error handling and transaction ownership. Unconditionally committing or rolling back a caller’s transaction can be incorrect. Procedures do not automatically prevent injection: concatenated dynamic SQL remains unsafe. Match parameter types to column types. Parameter sniffing describes compilation influenced by parameter values; do not add RECOMPILE without measuring.
Organise parameterised report calls.
Expecting RETURN to return a whole table.
One topic. Three levels of depth.
DECLARE @CustomerId int = 1;
SELECT OrderId, OrderDate FROM lab.SalesOrder WHERE CustomerId = @CustomerId;Shows a parameter used in a query.
This page does not execute SQL. Practise in the downloadable SqlStudioLab using SSMS. Before rerunning temporary-table examples, remove only the relevant #table. Views, procedures and functions create persistent lab objects; never use a production connection.
Try it yourself first.
Call GetCustomerOrders for customer two.
Show the solution and explanation
EXEC lab.GetCustomerOrders @CustomerId = 2;Create the procedure first. Orders 102 and 108 are returned.