A stored procedure is SQL saved inside the database under a name, so it can be run again by calling that name. It can take parameters, values passed in each time it is run, which makes one procedure serve many similar requests.
Procedures keep a frequently used query in one place, let applications call it without knowing how it works, and let you grant people permission to run a procedure without giving them access to the tables underneath.
The syntax differs a great deal between databases. The examples on this page are for SQL Server, and use the Invoices table from the example database.
Creating and running a procedure
Section titled “Creating and running a procedure”CREATE PROCEDURE ListUnpaidInvoicesASSELECT InvoiceID, Supplier, AmountFROM InvoicesWHERE PaidDate IS NULL;Run it with EXEC:
EXEC ListUnpaidInvoices;| InvoiceID | Supplier | Amount |
|---|---|---|
| 1003 | Ashby Camera Hire | 41,250.00 |
| 1004 | Kestrel Catering | 2,940.00 |
With a parameter
Section titled “With a parameter”Parameters are named with an @ and given a type. This version lists the unpaid invoices for one production:
CREATE PROCEDURE ListUnpaidInvoicesFor @ProductionID intASSELECT InvoiceID, Supplier, AmountFROM InvoicesWHERE ProductionID = @ProductionID AND PaidDate IS NULL;Pass the value when you call it:
EXEC ListUnpaidInvoicesFor @ProductionID = 1;| InvoiceID | Supplier | Amount |
|---|---|---|
| 1003 | Ashby Camera Hire | 41,250.00 |
For several parameters, list them separated by commas, both when creating the procedure (@ProductionID int, @Supplier nvarchar(100)) and when calling it.
Other databases
Section titled “Other databases”- PostgreSQL has
CREATE PROCEDUREfor actions andCREATE FUNCTIONfor queries that return rows, written in its own procedural language and run withCALLorSELECT. - MySQL uses
CREATE PROCEDUREwith aBEGIN … ENDbody and runs it withCALL. - Oracle writes procedures in PL/SQL.
- SQLite has no stored procedures; the application holds the queries instead.