- Kimberly Collins
- SQL Server database developer for 17 years
- github.com/kacollins/stored-procedures
A collection of SQL statements stored on the database server for later execution
- Can have input and output parameters
- SQL statement(s) to select or modify data
- Often abbreviated
SP
orSPROC
CREATE PROCEDURE ProcedureName
@Parameter1 DataType,
@Parameter2 DataType
AS
BEGIN
--SQL statement(s) defining the logic of the stored procedure
END
CREATE PROCEDURE GetEmployeeDetails
@EmployeeID INT
AS
BEGIN
SELECT *
FROM Employees
--Probably join to some other tables
WHERE EmployeeID = @EmployeeID
END
View | Stored Procedure |
---|---|
* Represents a virtual table based on a predefined query | * Can use variables and one or more SQL statements to select or modify |
* Can't have variables, multiple statements, or parameters | * Can have input and output parameters |
SELECT * FROM EmployeeSummary WHERE EmployeeID = 123 |
EXEC GetEmployeeDetails 123 |
Function | Stored Procedure |
---|---|
* Returns a single value or a table that can be used in SQL | * Can have output parameters but doesn't necessarily return data |
* Not intended to modify data | * Can be used to modify data |
SELECT GETDATE() SELECT Value FROM STRING_SPLIT('1,2,3', ',') |
EXEC GetEmployeeDetails 123 |
SUM, AVG, COUNT, etc.
Updating large sets of data in a single operation
Complex joins
- Single stored procedure call reduces network traffic
- Transaction ensures that the entire set succeeds or fails as a single unit
- Query plan caching
- Indexes
- Reports
- Called from back end
- Never - some teams want all business logic in the application code
- Always - some teams use stored procedures for all data access
- As needed, usually along with an ORM
- Techlahoma's Slack
#databases
channel@KimberlyCollins
- github.com/kacollins/stored-procedures