Stored procedures and functions are vital components of SQL programming, enabling encapsulation of logic, code reuse, and efficient execution of complex database tasks. This chapter delves into advanced concepts, techniques, and practices for working with stored procedures and functions, providing a detailed understanding of their capabilities and use cases.
Stored Procedures are precompiled collections of SQL statements that perform a specific task.
Functions are similar but are designed to return a value and are typically used in expressions.
Feature | Stored Procedures | Functions |
---|---|---|
Return Type | Can return multiple values | Must return a single value |
Use in Queries | Not used in SELECT statements | Used in SELECT statements |
Transaction Handling | Can contain transaction control | Cannot include transaction control |
Performance | Optimized for executing tasks | Optimized for computations |
CREATE PROCEDURE GetEmployeeDetails
@Department NVARCHAR(50),
@MinSalary INT
AS
BEGIN
SELECT Name, Department, Salary
FROM Employees
WHERE Department = @Department AND Salary > @MinSalary;
END;
GO
EXEC GetEmployeeDetails 'HR', 50000;
Allow returning values from a procedure.
CREATE PROCEDURE GetDepartmentCount
@Department NVARCHAR(50),
@Count INT OUTPUT
AS
BEGIN
SELECT @Count = COUNT(*)
FROM Employees
WHERE Department = @Department;
END;
GO
DECLARE @Result INT;
EXEC GetDepartmentCount 'HR', @Result OUTPUT;
PRINT 'Total Employees: ' + CAST(@Result AS NVARCHAR);
Handle hierarchical data.
CREATE PROCEDURE GetEmployeeHierarchy
@ManagerID INT
AS
BEGIN
SELECT EmployeeID, Name
FROM Employees
WHERE ManagerID = @ManagerID;
EXEC GetEmployeeHierarchy @ManagerID; -- Recursive Call
END;
GO
Return a table as output.
CREATE FUNCTION GetHighSalaryEmployees(@MinSalary INT)
RETURNS TABLE
AS
RETURN (
SELECT Name, Salary FROM Employees WHERE Salary > @MinSalary
);
GO
SELECT * FROM GetHighSalaryEmployees(60000);
Perform complex calculations.
CREATE FUNCTION CalculateBonus(@Salary INT, @BonusRate DECIMAL(5, 2))
RETURNS DECIMAL(10, 2)
AS
BEGIN
RETURN @Salary * @BonusRate;
END;
GO
SELECT dbo.CalculateBonus(50000, 0.1);
Dynamic SQL allows generating and executing queries dynamically at runtime.
CREATE PROCEDURE SearchEmployees
@Column NVARCHAR(50),
@Value NVARCHAR(50)
AS
BEGIN
DECLARE @DynamicSQL NVARCHAR(MAX);
SET @DynamicSQL = 'SELECT * FROM Employees WHERE ' + @Column + ' = ''' + @Value + '''';
EXEC(@DynamicSQL);
END;
GO
EXEC SearchEmployees 'Department', 'HR';
CREATE PROCEDURE SafeInsertEmployee
@Name NVARCHAR(50),
@Department NVARCHAR(50),
@Salary INT
AS
BEGIN
BEGIN TRY
INSERT INTO Employees (Name, Department, Salary)
VALUES (@Name, @Department, @Salary);
END TRY
BEGIN CATCH
PRINT 'Error: ' + ERROR_MESSAGE();
END CATCH;
END;
GO
OPTION (RECOMPILE)
if necessary.Advanced stored procedures and functions offer powerful tools for efficient database programming. By mastering concepts like dynamic SQL, error handling, and optimization, developers can create robust, secure, and high-performance database solutions. The techniques and examples provided in this chapter ensure a thorough understanding of advanced SQL programming, empowering you to handle complex scenarios with confidence. Happy coding !❤️