SQL Stored Procedures for SQL Server
What is a Stored Procedure?
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.
With the help of SQL query you can write over and over again, save it as a stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.
Stored Procedure Syntax:
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXEC procedure_name ;
Demo Employee table
This employee table is used for examples:
Stored Procedure Example
The following SQL statement creates a stored procedure named "SelectAllemployee" that selects all records from the "employee" table:
Example:
CREATE PROCEDURE SelectAllemployeeAS
SELECT * FROM employee
GO;
Example:
EXEC SelectAllemployee;
Stored Procedure With One Parameter
The below SQL statement creates a stored procedure that selects employee from a particular country from the "employee" table:
Example:
CREATE PROCEDURE SelectAllemployee @Country nvarchar(30)AS
SELECT * FROM employee
WHERE Country = @Country
GO;
Example:
EXEC SelectAllemployee @Country = 'India' ;
Stored Procedure With Multiple Parameters
Setting up multiple parameters is very easy. Just list each parameter and the data type separated by a comma as shown below.
The following SQL statement creates a stored procedure that selects employee from a particular Country with a particular Pincode from the "employee" table:
Example:
CREATE PROCEDURE SelectAllemployee @Country nvarchar(30), @Pincode nvarchar(10)AS
SELECT * FROM employee
WHERE Country = @Country AND Pincode = @Pincode
GO;
Example:
EXEC SelectAllemployee @Country = 'India' , @Pincode = '825301' ;