A SQL stored procedure is a group of Transact-SQL statements compiled into a single execution plan. SQL stored procedures return data in various ways, such as:
- Output parameters, which generally return data such as an integer or character value, but can even return a cursor variable.
This is the most common return.
- Return codes (integer value)
- A result set for each SELECT statement contained in the stored procedure or other stored procedures.
Stored procedures assist in creating a implementation of logic across various client applications. The SQL statements needed to perform a common task can be packaged as a stored procedure, and each application needing to perform
that task can then use the existing stored procedure without having to build more logic. Another benefit is that applications do not need to send all of the SQL statements when communicating with the database. They only have to EXECUTE a procedure by name and provide the values of the parameters.
This also ensures that users are shielded from needing to know the details of the tables in the database.
Here is an example of how to create a stored procedure.
CREATE PROCEDURE procedureName
SELECT columnName FROM tableName;
CREATE PROCEDURE procEmpList
SELECT empID, empName FROM Employees;
Once the stored procedure is created, you can simply execute this procedure by using the following syntax.
The results will look something like this:
This is, of course, a very simple example. The power of the stored procedure is easily seen when you include the use of parameters in your stored procedure.
Recommended Books & Training Resources