A stored procedure is a precompiled T-SQL program that you save in the database and execute on demand.
A stored procedure is a named block of T-SQL statements stored in the database. Because it is precompiled, it runs faster than sending ad-hoc SQL and centralizes business logic for reuse and security.
Use CREATE PROCEDURE
followed by the procedure name, parameters, and the body wrapped in AS ... BEGIN ... END
. Always qualify the name with its schema (dbo
by default) to avoid ambiguity.
CREATE PROCEDURE dbo.GetCustomerOrders @CustomerId INT AS BEGIN ... END
creates a reusable query that returns orders for one customer.
Run EXEC dbo.GetCustomerOrders @CustomerId = 42;
or the shorter EXEC GetCustomerOrders 42;
. You can also use sp_executesql
when you need dynamic SQL inside the procedure.
Use ALTER PROCEDURE
to change the definition without losing permissions. Use DROP PROCEDURE dbo.GetCustomerOrders;
to remove it completely.
Choose procedures when you need to encapsulate complex joins, ensure consistent filters, improve performance with plan caching, or restrict direct table access for security.
1) Always set SET NOCOUNT ON;
to avoid extra result sets.
2) Validate parameters at the top.
3) Return data via SELECT
or output parameters, not PRINT
.
4) Keep procedures focused on one task for easier maintenance.
The sample procedure below joins Customers
, Orders
, and OrderItems
to return total spend per customer within a date range.
Yes. Use RETURN int_value
for status codes or define OUTPUT parameters to send data back to the caller.
Use SQL Server Management Studio’s debugger or insert temporary logging with PRINT
and table variables. For performance tuning, capture execution plans with SET STATISTICS PROFILE ON
.
Often yes, because the execution plan is cached once and reused. However, well-written parameterized queries can achieve similar performance; choose procedures for encapsulation and security benefits.