document18
document18
Dr M AOUDE
February 4, 2025
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
GetEmployeeDetails
CREATE PROCEDURE GetEmployeeDetails
@EmployeeID INT
AS
BEGIN
SELECT * FROM Employees
WHERE EmployeeID = @EmployeeID;
END;
sp_help Example
EXEC sp_help ’Employees’;
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;
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;
Syntax:
EXEC procedure_name;
Example:
EXEC GetEmployeeInfo;
SecureProcedure Example
CREATE PROCEDURE SecureProcedure
WITH ENCRYPTION, EXECUTE AS ’AdminUser’
AS
BEGIN
SELECT * FROM SensitiveData;
END;
Example: SecureProcedure
CREATE PROCEDURE SecureProcedure
WITH ENCRYPTION, EXECUTE AS ’AdminUser’
AS
BEGIN
SELECT * FROM SensitiveData;
END;
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;
Enable CLR
sp_configure ’clr_enabled’, 1;
RECONFIGURE;
Example: CLRProcedure
CREATE PROCEDURE CLRProcedure
AS EXTERNAL NAME MyAssembly.MyClass.MyMethod;
Recompile Hints:
WITH RECOMPILE on procedure or EXEC statement
sp_recompile <proc_name>
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;