bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/SQL/SQL Tutorial
SQL•SQL Tutorial

SQL Stored Procedures

Concept visual

SQL Stored Procedures

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

What is a Stored Procedure?

A stored procedure is a precompiled SQL code that can be saved and reused. If you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to execute it. A stored procedure can also have parameters, so it can act based on the parameter value(s) that is passed.

Key Benefits of Stored Procedures

Stored procedures are widely used in database management, and have the following benefits:

Formula

Code Reusability - The same procedure can be called from various applications
Improved Performance - Stored procedures are precompiled and runs faster
Database Security - You can set users permission to run a specific procedure (limits direct access to tables)
Easy Maintenance - When updating a procedure, it automatically updates all its use

Stored Procedure Syntax (SQL Server) To create a stored procedure, use the CREATE PROCEDURE statement:

Create Procedure

procedure_name @param1 datatype, @param2 datatype AS

Begin

-- SQL_statements to be executed

Select

column1, column2

From

table_name

Where

columnN = @paramN

;
END;

Tip:

To see the syntax for MySQL database, look at MySQL Stored Procedures.

Execute a Stored Procedure

To run a stored procedure, use the EXEC statement:

Exec

procedure_name @param1 = 'value1', @param2 = 'value2'

;

Drop a Stored Procedure

To delete a stored procedure, use the DROP PROCEDURE statement:

Drop Procedure

procedure_name

;

Tip:

To ensure that

Drop Procedure

does not return an error, if the procedure is missing, add the IF EXISTS

clause:

Drop Procedure If Exists

procedure_name

;

Demo Database

Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID

CustomerName

ContactName

Address

City

PostalCode

Country

Previous

SQL NULL Functions

Next

SQL Comments