A stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
Stored procedures in SQL Server are similar to procedures in other programming languages in that they can:
- Accept input parameters and return multiple values in the form of output parameters to the calling procedure or batch.
- Contain programming statements that perform operations in the database, including calling other procedures.
- Return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure).
You can use the Transact-SQL EXECUTE statement to run a stored procedure. Stored procedures are different from functions in that they do not return values in place of their names and they cannot be used directly in an expression.
The benefits of using stored procedures in SQL Server rather than Transact-SQL programs stored locally on client computers are:
- They allow modular programming.
- They allow faster execution.
- They can reduce network traffic.
- They can be used as a security mechanism.
Stored Procedures supported by SQL Server:
SQL Server supports five types of stored procedures. They are:
System Stored Procedures (sp_)
Many administrative and informational activities SQL Server can be performed through system stored procedures. These system stored procedures are stored in the Master database and are identified by the sp_prefix. They can be executed from any database.
Local Stored Procedures
These procedures will be created in the user database. The user who creates the procedure will become the owner for that procedure.
Temporary Stored Procedures
Temporary stored procedures are stored in tempdb database. They can be used in the case where an application builds dynamic Transact-SQL statements that are executed several times. Instead of recompiling the T-SQL statements each time, a temporary stored procedure can be created and compiled on the first execution, then execute the precompiled plan multiple times. The temporary stored procedures can be local or global.
Remote Stored Procedures
They are legacy feature of SQL Server. Their functionality in T-SQL is limited to executing a stored procedure on a remote SQL Server installation. The distributed queries in SQL Server support this ability along with the ability to access tables on linked OLEDB data sources directly from local T_SQL statements.
Extended Stored Procedures
These are dynamic link libraries (DLLs) that SQL Server can dynamically load and execute. These procedures run directly in the address space of SQL Server and are programmed using the SQL Server Open Data Services API. They are identified by the xp_prefix.
Creating a Stored Procedure
The stored procedures can be created using the CREATE PROCEDURE statement.
Example: creating a procedure to insert values into emp table.
Ex: Executing the Procedure: