Stored Procedures



Stored Procedures in SQL Server


A stored procedure is a type of code in SQL that can be stored for later use and can be used many times. So, whenever we need to execute the query, instead of calling it you can just call the stored procedure. Values can be passed through stored procedures.

These are of two types:

* Stored procedure with One parameter

* Stored procedure with Multiple parameters

Syntax

CREATE PROCEDURE procedure_name
AS
sql_statement
GO;

Execute a Stored Procedure

EXEC procedure_name;

Now,let us consider a customers table:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1RajivlalRajaRamnagar 124Hyderabad05021India
2BanveerjiBannuRajivnagar 114AhmednagarWA1 1DPIndia

Stored Procedure Example

The following SQL statement creates a stored procedure named "SelectAllCustomers" that selects all records from the "Customers" table:

Example

CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;

Execute the stored procedure above as follows:

Example

EXEC SelectAllCustomers;

1.Stored Procedure With One Parameter

The following SQL statement creates a stored procedure that selects Customers from a particular City from the "Customers" table:

Example

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;

Execute the stored procedure above as follows:

Example

EXEC SelectAllCustomers City = "Ahmednagar";

2.Stored Procedure With Multiple Parameters

Setting up multiple parameters is very easy.The following SQL statement creates a stored procedure that selects Customers from a particular City with a particular PostalCode from the "Customers" table:

Example

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;

Execute the stored procedure above as follows:

Example

EXEC SelectAllCustomers City = "Ahmednagar", PostalCode = "WA1 1DP";


Connection String

SQL Server Connection String Formats

posted on 2019-08-27 05:53:53 - SQL Server Tutorials


UNION

union in SQL server

posted on 2019-08-09 23:05:33 - SQL Server Tutorials


System Functions

System Functions in SQL Server

posted on 2019-08-09 06:14:33 - SQL Server Tutorials


Prompt Examples

ChatGPT Prompt Examples

posted on 2023-06-21 22:37:19 - ChatGPT Tutorials


Use Cases

Chat GPT Key Use Cases

posted on 2023-06-21 21:03:17 - ChatGPT Tutorials


Prompt Frameworks

Prompt Frameworks

posted on 2023-06-21 19:33:06 - ChatGPT Tutorials