Roadmap › SQL Server & T-SQL › Module: Programmability
Lessons in this course (19)
10. Stored procedures
Intermediate★ Must knowLesson 10 of 19
sql
CREATE OR ALTER PROCEDURE dbo.usp_GetEmployeesByDept
@DeptId INT,
@MinSalary DECIMAL(12,2) = 0, -- default
@TotalCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON; -- suppress "n rows affected" messages
SELECT EmpId, FullName, Salary FROM dbo.Employees
WHERE DeptId = @DeptId AND Salary >= @MinSalary
ORDER BY Salary DESC;
SELECT @TotalCount = @@ROWCOUNT;
RETURN 0; -- return value: status code (INT only)
END;
GO
DECLARE @n INT;
EXEC dbo.usp_GetEmployeesByDept @DeptId = 1, @MinSalary = 50000, @TotalCount = @n OUTPUT;
SELECT @n;Benefits: plan reuse, security (grant EXECUTE without table access), fewer round trips, encapsulated logic, protection against injection (when not building dynamic SQL inside). Dynamic SQL inside a proc must use sp_executesql with parameters.