0% found this document useful (0 votes)
8 views

document18

The document provides an overview of stored procedures in SQL Server, detailing their purpose, types, creation, and management. It highlights the benefits of using stored procedures, such as improved performance, security, and error handling, along with best practices for implementation. Additionally, it covers advanced topics like CLR integration and optimization techniques for efficient execution.

Uploaded by

Dima Azzam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

document18

The document provides an overview of stored procedures in SQL Server, detailing their purpose, types, creation, and management. It highlights the benefits of using stored procedures, such as improved performance, security, and error handling, along with best practices for implementation. Additionally, it covers advanced topics like CLR integration and optimization techniques for efficient execution.

Uploaded by

Dima Azzam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Stored Procedures in SQL Server

Boosting Efficiency and Security

Dr M AOUDE

February 4, 2025

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 1 / 29


Lesson 9: Overview

Skills Matrix:
Understand the purpose and types of stored procedures
Learn how to create, modify, and manage stored procedures
Explore input/output parameters, error handling, and CLR integration
Understand the compilation and optimization process of stored
procedures
Apply best practices for deploying and using stored procedures

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 2 / 29


1. What Are Stored Procedures?

Precompiled batches of SQL statements stored as database objects


Can accept input parameters and return output parameters or result
sets
Improve performance, security, and reusability

GetEmployeeDetails
CREATE PROCEDURE GetEmployeeDetails
@EmployeeID INT
AS
BEGIN
SELECT * FROM Employees
WHERE EmployeeID = @EmployeeID;
END;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 3 / 29


2. Types of Stored Procedures

System Stored Procedures:


Predefined, start with sp_ (e.g., sp_help, sp_who)
User-Defined Stored Procedures:
Created by users for custom tasks
Extended Stored Procedures:
Legacy, start with xp_ (e.g., xp_cmdshell)

sp_help Example
EXEC sp_help ’Employees’;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 4 / 29


2. Types of Stored Procedures

SQL Server supports three types of stored procedures:


System Stored Procedures: Predefined procedures starting with
sp_ (e.g., sp_help, sp_who).
User-Defined Stored Procedures: Custom procedures created by
users.
Extended Stored Procedures: Legacy procedures starting with xp_
(e.g., xp_cmdshell).

Example: System Stored Procedure


EXEC sp_help ’Employees’;

This command provides information about the Employees table.

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 5 / 29


Different Flavors of Stored Procedures

System Stored Procedures:


Built-in procedures starting with sp_ (e.g., sp_help, sp_who2).
User-Defined Stored Procedures:
Created by users for specific tasks.
Extended Stored Procedures:
External routines written in languages like C or C++. (Less common
now with CLR integration.)

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 6 / 29


3. Creating Stored Procedures
Syntax:
CREATE PROCEDURE <procedure_name>
[(@param1 datatype [= default], ...)]
AS
BEGIN
– SQL code
END;

AddEmployee Example
CREATE PROCEDURE AddEmployee
@FirstName NVARCHAR(50),
@LastName NVARCHAR(50),
@HireDate DATE
AS
BEGIN
INSERT INTO Employees (FirstName, LastName, HireDate)
VALUES (@FirstName, @LastName, @HireDate);
END;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 7 / 29


3. Creating Stored Procedures

Use the CREATE PROCEDURE statement to define a stored procedure.


Example: AddEmployee
CREATE PROCEDURE AddEmployee
@FirstName NVARCHAR(50),
@LastName NVARCHAR(50),
@HireDate DATE
AS
BEGIN
INSERT INTO Employees (FirstName, LastName, HireDate)
VALUES (@FirstName, @LastName, @HireDate);
END;

This procedure adds a new employee to the Employees table.

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 8 / 29


Your First Stored Procedure

Syntax:
CREATE PROCEDURE procedure_name
AS
BEGIN
– SQL statements
END;

Example:
GetEmployeeInfo
CREATE PROCEDURE GetEmployeeInfo
AS
BEGIN
SELECT employee_id, first_name, last_name
FROM Employees;
END;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 9 / 29


Running the Code

Syntax:
EXEC procedure_name;

Example:
EXEC GetEmployeeInfo;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 10 / 29


4. Using Procedure Options

WITH ENCRYPTION: Encrypts the procedure definition


WITH RECOMPILE: Forces recompilation each time it’s run
WITH EXECUTE AS: Executes under a specific user’s security
context

SecureProcedure Example
CREATE PROCEDURE SecureProcedure
WITH ENCRYPTION, EXECUTE AS ’AdminUser’
AS
BEGIN
SELECT * FROM SensitiveData;
END;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 11 / 29


4. Using Procedure Options

WITH ENCRYPTION: Encrypts the procedure definition to protect


intellectual property.
WITH RECOMPILE: Forces recompilation of the procedure every time
it is executed.
WITH EXECUTE AS: Executes the procedure under a specific user’s
security context.

Example: SecureProcedure
CREATE PROCEDURE SecureProcedure
WITH ENCRYPTION, EXECUTE AS ’AdminUser’
AS
BEGIN
SELECT * FROM SensitiveData;
END;

This procedure is encrypted and runs under the AdminUser security


context.
Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 12 / 29
Security and Encryption
Using WITH ENCRYPTION: Prevent others from viewing your
procedure’s code:
Example: ProcessSensitiveData
CREATE PROCEDURE ProcessSensitiveData
WITH ENCRYPTION
AS
BEGIN
SELECT * FROM ConfidentialTable;
END;

Using EXECUTE AS: Run procedures under specific security contexts:


Example: UpdateEmployeeSalary
CREATE PROCEDURE UpdateEmployeeSalary
WITH EXECUTE AS OWNER
AS
BEGIN
UPDATE Employees
SET Salary = Salary * 1.1
WHEREDr Department
M AOUDE
= ’Sales’;
Stored Procedures in SQL Server February 4, 2025 13 / 29
5. Input and Output Parameters

Input Parameter: Pass a value into the procedure Output Parameter:


Return a value from the procedure
GetEmployeeCount Example
CREATE PROCEDURE GetEmployeeCount
@DepartmentID INT,
@EmployeeCount INT OUTPUT
AS
BEGIN
SELECT @EmployeeCount = COUNT(*)
FROM Employees
WHERE DepartmentID = @DepartmentID;
END;
DECLARE @Count INT;
EXEC GetEmployeeCount @DepartmentID = 1, @EmployeeCount = @Count OUTPUT;
PRINT @Count;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 14 / 29


5. Input and Output Parameters
Input Parameters: Pass values into the procedure. Output Parameters:
Return values from the procedure.
Example: GetEmployeeCount
CREATE PROCEDURE GetEmployeeCount
@DepartmentID INT,
@EmployeeCount INT OUTPUT
AS
BEGIN
SELECT @EmployeeCount = COUNT(*)
FROM Employees
WHERE DepartmentID = @DepartmentID;
END;

This procedure returns the number of employees in a specific department.


Executing the Procedure:
DECLARE @Count INT;
EXEC GetEmployeeCount @DepartmentID = 1, @EmployeeCount = @Count OUTPUT;
PRINT @Count;
Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 15 / 29
Parameters and Error Handling
Input and Output Parameters:
Example: CalculateEmployeeBonus
CREATE PROCEDURE CalculateEmployeeBonus
@EmployeeID INT,
@SalesAmount DECIMAL(18,2),
@BonusAmount DECIMAL(18,2) OUTPUT
AS
BEGIN
SET @BonusAmount = @SalesAmount * 0.05;
UPDATE Employees
SET YearlyBonus = @BonusAmount
WHERE EmployeeID = @EmployeeID;
END;

Executing the Procedure:


DECLARE @Bonus DECIMAL(18,2);
EXEC CalculateEmployeeBonus
@EmployeeID = 123,
@SalesAmount
Dr M AOUDE
= 50000, Stored Procedures in SQL Server February 4, 2025 16 / 29
6. Error Handling
TRY...CATCH: Handle exceptions gracefully
ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_SEVERITY(), etc.
to get details
UpdateSalary Example
CREATE PROCEDURE UpdateSalary
@EmployeeID INT,
@NewSalary DECIMAL(18,2)
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
UPDATE Employees
SET Salary = @NewSalary
WHERE EmployeeID = @EmployeeID;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
PRINT
Dr M ’Error:
AOUDE ’ + ERROR_MESSAGE();
Stored Procedures in SQL Server February 4, 2025 17 / 29
6. Error Handling
Use TRY...CATCH blocks to handle errors gracefully.
Example: UpdateSalary
CREATE PROCEDURE UpdateSalary
@EmployeeID INT,
@NewSalary DECIMAL(18, 2)
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
UPDATE Employees
SET Salary = @NewSalary
WHERE EmployeeID = @EmployeeID;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
PRINT ’Error: ’ + ERROR_MESSAGE();
END CATCH
END;
Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 18 / 29
Graceful Error Handling

Syntax:
BEGIN TRY
– SQL statements that might cause an error
END TRY
BEGIN CATCH
– Error handling statements
SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS
ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS
ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS
ErrorMessage; END CATCH;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 19 / 29


7. Modifying Stored Procedures

ALTER PROCEDURE: Modify an existing procedure


DROP PROCEDURE: Remove a procedure (also drops permissions)

ALTER Procedure Example


ALTER PROCEDURE GetEmployeeDetails
@EmployeeID INT,
@IncludeTerminated BIT = 0
AS
BEGIN
IF @IncludeTerminated = 1
SELECT * FROM Employees WHERE EmployeeID = @EmployeeID;
ELSE
SELECT * FROM Employees
WHERE EmployeeID = @EmployeeID AND IsTerminated = 0;
END;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 20 / 29


7. Modifying Stored Procedures

Use ALTER PROCEDURE to modify an existing procedure without dropping


it.
Example: Modify GetEmployeeDetails
ALTER PROCEDURE GetEmployeeDetails
@EmployeeID INT,
@IncludeTerminated BIT = 0
AS
BEGIN
IF @IncludeTerminated = 1
SELECT * FROM Employees WHERE EmployeeID = @EmployeeID;
ELSE
SELECT * FROM Employees WHERE EmployeeID = @EmployeeID AND
IsTerminated = 0;
END;

This modification adds an optional parameter to include terminated


employees.

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 21 / 29


8. Common Language Runtime (CLR) Procedures

Write stored procedures in a .NET language (C# or VB.NET)


CREATE ASSEMBLY to register the DLL
CREATE PROCEDURE referencing the .NET method
Must enable CLR:

Enable CLR
sp_configure ’clr_enabled’, 1;
RECONFIGURE;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 22 / 29


8. Common Language Runtime (CLR) Stored Procedures

CLR procedures allow you to write stored procedures in .NET languages


like C# or VB.NET.
Enable CLR integration:
Enable CLR
sp_configure ’clr_enabled’, 1;
RECONFIGURE;

Create a .NET assembly and deploy it to SQL Server.


Define the procedure using the assembly.

Example: CLRProcedure
CREATE PROCEDURE CLRProcedure
AS EXTERNAL NAME MyAssembly.MyClass.MyMethod;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 23 / 29


9. Compilation and Optimization

1 Parsing: Syntax check


2 Normalization: Validate object/column names
3 Compilation: Generate query plan
4 Optimization: Find least-cost query plan

Recompile Hints:
WITH RECOMPILE on procedure or EXEC statement
sp_recompile <proc_name>

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 24 / 29


9. Compilation and Optimization

SQL Server compiles and caches execution plans for stored procedures.
Use WITH RECOMPILE to force recompilation when necessary.
Example: Recompile GetEmployeeDetails
EXEC GetEmployeeDetails @EmployeeID = 1 WITH RECOMPILE;

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 25 / 29


10. Best Practices

Avoid sp_ prefix to prevent conflicts with system procedures


Test procedures thoroughly in dev before production
Keep each procedure focused on a single unit of work
Use transactions and error handling to maintain data integrity
Fully qualify object names (e.g., dbo.Employees)

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 26 / 29


10. Best Practices

Use meaningful names (e.g., up_ for user procedures).


Avoid using sp_ for custom procedures to prevent conflicts with
system procedures.
Test procedures in a development environment before deploying to
production.
Use transactions and error handling to maintain data integrity.

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 27 / 29


Key Benefits of Stored Procedures

Stored procedures offer numerous benefits, including:


Improved security through encapsulation
Reduced network traffic
Better performance through plan caching
Simplified maintenance
Protection against SQL injection attacks
When designing stored procedures, focus on:
Single responsibility principle
Proper error handling
Parameter validation
Appropriate security context
Performance optimization
Clear documentation
Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 28 / 29
11. Summary

Stored procedures reduce network traffic, encapsulate business logic,


and improve security
They can accept input, return output, and handle errors with
TRY...CATCH
CLR procedures let you use .NET code in the database
Recompilation and optimization ensure efficient execution plans

Dr M AOUDE Stored Procedures in SQL Server February 4, 2025 29 / 29

You might also like