In this article you will learn about how to create a stored procedure in SQL without parameter and with parameter .This article is useful for beginner who want to learn how to create SP.
What is a Stored Procedure?
A SQL stored procedure (SP) is a collection SQL statements and sql command logic, which is compiled and stored on the database. Stored procedues in SQL allows us to create SQL queries to be stored and executed on the server. Stored procedures can also be cached and reused. The main purpose of stored procedures to hide direct SQL queries from the code and improve performance of database operations such as select, update, and delete data.
You can create and execute stored procedures using the Object Explorer in SQL Server or using SQL Server Management Studio (SSMS).
So let's start with how to create a stored procedure without parameter.
- CREATE PROCEDURE stpGetAllUserDetail
- AS
- BEGIN
-
- Select * from tblUserDetail
- END
What are parameters in stored procedures?
Parameters in SPs are used to pass input values and return output values. There are two types of parameters:
- Input parameters - Pass values to a stored procedure.
- Output parameters - Return values from a stored procedure.
How to create a SELECT query SP with parameters?
In the previous steps, we created a simple SP that returned all rows from a table. Now, let's create a new SP that will take a city name as an inpurt parameter and will return all rows where city name matches the input parameter value.
Here is the updated SP with a parameter @CityName.
- GO
-
-
-
-
-
- CREATE PROCEDURE stpGetAllUserDetailByCityName
-
- @CityName nvarchar(30)
- AS
- BEGIN
-
-
-
- SET NOCOUNT ON;
-
- Select * From tblUserDetail
- where City like '%'+@CityName+'%'
-
- END
- GO
How to create a INSERT query based stored procedure?
We can use an INSERT INTO SQL query to insert data into a table. The following SQL statement creates an INSERT SP with three parameters.
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
-
-
-
-
-
- CREATE PROCEDURE stpInsertUserDetail
- @Name varchar(50),
- @City varchar(25),
- @Phone varchar(15)
-
- AS
- BEGIN
-
-
- SET NOCOUNT ON;
-
- Insert into tblUserDetail (Name,City,Phone)
- Values (@Name,@City, @Phone)
-
- END
- GO
Thank you Hope it help to you !!!!
Arjun Walmiki