Mastering SQL Stored Procedures

Mastering SQL Stored Procedures

Introduction

Microsoft SQL Server’s stored procedures are a vital tool for database professionals, offering a means to encapsulate complex SQL queries and business logic. A stored procedure is a little bit like a Container in SQL. This blog post aims to deepen your understanding of stored procedures with practical examples, exploring their creation, usage, and various options.

What are Stored Procedures?

Stored procedures in SQL Server are precompiled T-SQL code that can be executed repeatedly. They are beneficial for improving performance, ensuring consistency, and enhancing security.

Creating a Stored Procedure

Basic Syntax

CREATE PROCEDURE ProcedureName AS BEGIN 
-- SQL statements 
END

Example 1: Simple Data Retrieval

Imagine a table Employees with columns EmployeeID, Name, and Department.

CREATE PROCEDURE GetEmployeeDetails 
AS 
BEGIN 
   SELECT EmployeeID, Name, Department FROM Employees;
END

Parameterised Stored Procedures

Parameters make stored procedures more flexible and dynamic.

Example 2: Data Retrieval with Parameters

Retrieve details of employees from a specific department:

CREATE PROCEDURE GetEmployeeByDepartment 
@DepartmentName VARCHAR(100
AS 
BEGIN 
   SELECT * FROM Employees WHERE Department = @DepartmentName; 
END

Execution

EXEC GetEmployeeByDepartment @DepartmentName = 'HR';

Modifying Data

Stored procedures can also insert, update, or delete data.

Example 3: Adding a New Employee

CREATE PROCEDURE AddNewEmployee 
@Name VARCHAR(100), 
@Department VARCHAR(100
AS 
BEGIN
   INSERT INTO Employees (Name, Department) 
   VALUES (@Name, @Department); 
END

Execution

EXEC AddNewEmployee @Name = 'John Doe', @Department = 'IT';

Advanced Options

Output Parameters

Stored procedures can return values using output parameters.

Example 4: Counting Employees in a Department

CREATE PROCEDURE CountEmployeesInDepartment 
@DepartmentName VARCHAR(100), 
@EmployeeCountINT 
OUTPUT AS 
BEGIN 
   SELECT @EmployeeCount = COUNT(*) FROM Employees 
   WHERE Department =@DepartmentName; 
END

Execution

DECLARE @Count INT
EXEC CountEmployeesInDepartment 
@DepartmentName = 'Sales'
@EmployeeCount = @Count OUTPUT

SELECT @Count AS EmployeeCount;

Handling Transactions

Stored procedures can manage transactions for data integrity.

Example 5: Updating Employee Department

CREATE PROCEDURE UpdateEmployeeDepartment 
@EmployeeID INT
@NewDepartment VARCHAR(100
AS
BEGIN 
   BEGIN TRANSACTION
      UPDATE Employees 
      SET Department = @NewDepartment 
      WHERE EmployeeID = @EmployeeID; 
   COMMIT TRANSACTION
END

Error Handling

Using TRY-CATCH

Stored procedures can handle errors gracefully using TRY-CATCH blocks.

Example 6: Error-Handling in Data Update

CREATE PROCEDURE SafeUpdateEmployee 
@EmployeeID INT
@NewDepartment VARCHAR(100
AS 
BEGIN
   BEGIN TRY 
      BEGIN TRANSACTION
         
         UPDATE Employees 
         SET Department = @NewDepartment 
         WHERE EmployeeID = @EmployeeID; 
     
      COMMIT TRANSACTION
   END TRY
   BEGIN CATCH 
       ROLLBACK TRANSACTION;
       SELECT ERROR_MESSAGE() AS ErrorMessage; 
   END CATCH END

Conclusion

Stored procedures in Microsoft SQL Server are a potent tool for managing complex operations efficiently and securely. By leveraging parameterisation, error handling, and transaction management, stored procedures offer a reliable and robust way to interact with your SQL databases. Whether inserting, updating, or querying data, these examples provide a solid foundation for harnessing the power of SQL Server’s stored procedures.

You can find the official documentation for stored procedures here: – https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/stored-procedures-database-engine?view=sql-server-ver16

I have also written several other blog posts about SQL Server here: – SQL Server Section

Stephen

Hi, my name is Stephen Finchett. I have been a software engineer for over 30 years and worked on complex, business critical, multi-user systems for all of my career. For the last 15 years, I have been concentrating on web based solutions using the Microsoft Stack including ASP.Net, C#, TypeScript, SQL Server and running everything at scale within Kubernetes.