Stored Procedures
Encapsulate business logic into reusable, precompiled SQL routines stored directly in the database.
- Reusability â Write once, call from anywhere without duplicating SQL code
- Security â Grant execution permissions without exposing underlying table access
- Performance â Precompiled execution plans reduce parsing overhead on repeated calls Stored procedures are the backbone of enterprise database applications.
What Is a Stored Procedure?
Once created, a stored procedure's SQL is parsed and its execution plan is cached by the database engine. Subsequent calls reuse the cached plan, avoiding re-parsing and re-optimization â a significant performance benefit for complex queries.
-- Create a simple stored procedure
CREATE PROCEDURE GetActiveCustomers
AS
BEGIN
SELECT customer_id, name, email, phone
FROM customers
WHERE status = 'ACTIVE'
ORDER BY name;
END;
-- Execute the procedure
EXEC GetActiveCustomers;
Creating Procedures with Parameters
-- Procedure with input and output parameters
CREATE PROCEDURE GetCustomerOrderSummary
@customer_id INT,
@total_orders INT OUTPUT,
@total_spent DECIMAL(10,2) OUTPUT
AS
BEGIN
SELECT
@total_orders = COUNT(*),
@total_spent = ISNULL(SUM(total), 0)
FROM orders
WHERE customer_id = @customer_id;
END;
-- Call with output parameters
DECLARE @orders INT, @spent DECIMAL(10,2);
EXEC GetCustomerOrderSummary
@customer_id = 42,
@total_orders = @orders OUTPUT,
@total_spent = @spent OUTPUT;
SELECT @orders AS TotalOrders, @spent AS TotalSpent;
Default Parameter Values
Parameters can have default values, making them optional when calling the procedure.
CREATE PROCEDURE SearchProducts
@category NVARCHAR(50) = NULL,
@min_price DECIMAL(10,2) = 0,
@max_price DECIMAL(10,2) = 999999,
@sort_by NVARCHAR(20) = 'name'
AS
BEGIN
SELECT product_id, name, category, price
FROM products
WHERE (@category IS NULL OR category = @category)
AND price BETWEEN @min_price AND @max_price
ORDER BY
CASE @sort_by
WHEN 'name' THEN name
WHEN 'price' THEN CAST(price AS NVARCHAR)
END;
END;
-- Call with various parameter combinations
EXEC SearchProducts; -- all products
EXEC SearchProducts @category = 'Electronics'; -- electronics only
EXEC SearchProducts @min_price = 50, @max_price = 200;
EXEC SearchProducts @category = 'Books', @sort_by = 'price';
Control Flow in Procedures
Procedures support conditional logic and loops for complex business rules.
CREATE PROCEDURE ProcessOrder
@order_id INT
AS
BEGIN
DECLARE @status NVARCHAR(20);
DECLARE @total DECIMAL(10,2);
SELECT @status = status, @total = total
FROM orders WHERE order_id = @order_id;
IF @status = 'CANCELLED'
BEGIN
PRINT 'Order is already cancelled.';
RETURN;
END
IF @total > 1000
BEGIN
UPDATE orders
SET status = 'PENDING_APPROVAL',
discount = @total * 0.10
WHERE order_id = @order_id;
INSERT INTO approval_queue (order_id, requested_by, request_date)
VALUES (@order_id, SYSTEM_USER, GETDATE());
END
ELSE
BEGIN
UPDATE orders
SET status = 'CONFIRMED'
WHERE order_id = @order_id;
INSERT INTO order_log (order_id, action, action_date)
VALUES (@order_id, 'AUTO_CONFIRMED', GETDATE());
END
END;
Modifying and Dropping Procedures
-- Alter an existing procedure
ALTER PROCEDURE GetActiveCustomers
@min_order_count INT = 0
AS
BEGIN
SELECT c.customer_id, c.name, c.email,
COUNT(o.order_id) AS order_count
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE c.status = 'ACTIVE'
GROUP BY c.customer_id, c.name, c.email
HAVING COUNT(o.order_id) >= @min_order_count
ORDER BY order_count DESC;
END;
-- Drop a procedure
DROP PROCEDURE IF EXISTS GetActiveCustomers;
-- Check if a procedure exists
IF OBJECT_ID('GetActiveCustomers', 'P') IS NOT NULL
PRINT 'Procedure exists';
ELSE
PRINT 'Procedure does not exist';
Error Handling in Procedures
CREATE PROCEDURE TransferFunds
@from_account INT,
@to_account INT,
@amount DECIMAL(10,2)
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION;
-- Validate sufficient balance
DECLARE @balance DECIMAL(10,2);
SELECT @balance = balance FROM accounts WHERE id = @from_account;
IF @balance < @amount
BEGIN
RAISERROR('Insufficient funds. Available: %.2f', 16, 1, @balance);
RETURN;
END
UPDATE accounts SET balance = balance - @amount WHERE id = @from_account;
UPDATE accounts SET balance = balance + @amount WHERE id = @to_account;
INSERT INTO transfers (from_id, to_id, amount, transfer_date)
VALUES (@from_account, @to_account, @amount, GETDATE());
COMMIT;
PRINT 'Transfer completed successfully.';
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK;
DECLARE @msg NVARCHAR(4000) = ERROR_MESSAGE();
DECLARE @sev INT = ERROR_SEVERITY();
RAISERROR(@msg, @sev, 1);
END CATCH
END;
Advantages Over Inline SQL
| Feature | Stored Procedure | Inline SQL |
|---|---|---|
| Performance | Precompiled execution plan | Parsed on every execution |
| Security | Granular EXECUTE permissions | Requires direct table access |
| Network Traffic | Single call to execute | Full SQL text sent each time |
| Maintainability | Centralized, version-controlled logic | Scattered across application code |
| Reusability | Call from multiple applications | Duplicated across clients |
| SQL Injection | Parameters are safe by design | Requires careful escaping |
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions