Skip to content

SQL Stored Procedures for SQL Server

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.

CREATE PROCEDURE ListUnpaidInvoices
AS
SELECT InvoiceID, Supplier, Amount
FROM Invoices
WHERE 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

Parameters are named with an @ and given a type. This version lists the unpaid invoices for one production:

CREATE PROCEDURE ListUnpaidInvoicesFor @ProductionID int
AS
SELECT InvoiceID, Supplier, Amount
FROM Invoices
WHERE 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.

  • PostgreSQL has CREATE PROCEDURE for actions and CREATE FUNCTION for queries that return rows, written in its own procedural language and run with CALL or SELECT.
  • MySQL uses CREATE PROCEDURE with a BEGIN … END body and runs it with CALL.
  • Oracle writes procedures in PL/SQL.
  • SQLite has no stored procedures; the application holds the queries instead.