Stored Procedure in SQL
Stored Procedure in SQL
Lab Manual 11
Instructor:
• Mr. Nazeef Ul Haq (Lab)
Learning Objectives:
• Understanding of Stored Procedure and Views.
Helping Material:
A SQL stored procedure (SP) is a collection SQL statements and sql command logic, which is compiled and
stored on the database. Stored procedures 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.
T-SQL stored procedures: T-SQL (Transact SQL) SPs receive and returns parameters. These SPs
process the Insert, Update and Delete queries with or without parameters and return data of rows as
output. This is one of the most common ways to write SPs in SQL Server.
CLR stored procedures: CLR (Common Language Runtime) SPs are written in a CLR based
programming language such as C# or VB.NET and are executed by the .NET Framework.
Page 1 of 20
Let's login to our SQL Server database, so we can achieve the following:
• How to create a SELECT QUERY based stored procedure which return all records?
• How to create a PARAMETER based SELECT QUERY stored procedure which return records based on
parameters?
• How to create an INSERT query based stored procedure?
• How to create an UPDATE query based stored procedure?
• How to create a DELETE query based stored procedure?
Page 2 of 20
Empty stored procedure will be created using the following:
The empty template created by SQL Server for a SP looks like the following. The CREATE
PROCEDURE SQL command is used to create a procedure, followed by a SP name and its parameters.
The BEGIN and END area is used to define the query for the operation. This is where you will write a
select, update, insert, or delete queries.
1. -- ================================================
2. -- Template generated from Template Explorer using:
3. -- Create Procedure (New Menu).SQL
4. --
5. -- Use the Specify Values for Template Parameters
6. -- command (Ctrl-Shift-M) to fill in the parameter
7. -- values below.
8. --
9. -- This block of comments will not be included in
10. -- the definition of the procedure.
11. -- ================================================
12. SET ANSI_NULLS ON
13. GO
14. SET QUOTED_IDENTIFIER ON
15. GO
16. -- =============================================
17. -- Author: <Author,,Name>
18. -- Create date: <Create Date,,>
19. -- Description: <Description,,>
20. -- =============================================
21. CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
22. -- Add the parameters for the stored procedure here
23. <@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,
24. <@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
Page 3 of 20
25. AS
26. BEGIN
27. -- SET NOCOUNT ON added to prevent extra result sets from
28. -- interfering with SELECT statements.
29. SET NOCOUNT ON;
30.
31. -- Insert statements for procedure here
32. SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
33. END
34. GO
We must follow standard naming conventions which may also depend on your project and coding policies.
For user defined stored procedure naming conventions, my suggestions are to add one of the following prefixes
to your SP names.
1. sp
2. stp
3. stp_
4. udstp
5. udstp_
Naming conventions are just to identify objects. By adding these prefixes in the name, we can clearly identify
that this object is a stored procedure.
Before, we can create and execute any SPs, we need a database table. I create a database table named,
“tblMembers” using the following SQL query and execute it on the server. As you can see, my table has 4
column where the first column is an idenity column. Once the table is created, open table in your SSMS and add
some data by manually entering data to the table.
1. USE [MBKTest]
2. GO
3.
4. /****** Object: Table [dbo].[tblMembers] Script Date: 18-Nov-17,Sat 6:47:55 PM ******/
5. SET ANSI_NULLS ON
6. GO
7.
8. SET QUOTED_IDENTIFIER ON
9. GO
10.
11. SET ANSI_PADDING ON
12. GO
13.
Page 4 of 20
14. CREATE TABLE [dbo].[tblMembers](
15. [MemberID] [int] IDENTITY(1,1) NOT NULL,
16. [MemberName] [varchar](50) NULL,
17. [MemberCity] [varchar](25) NULL,
18. [MemberPhone] [varchar](15) NULL
19. )
20.
21. GO
22.
23. SET ANSI_PADDING OFF
24. GO
Click on your Database and expand “Programmability” item and right click on “Stored Procedures” or press
CTRL + N to get new query window. In the query area between BEGIN and END, type your SELECT
statement to select records from the table. See the Select statement in the below code.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author: Manoj Kalla
7. -- Create date: 18th Nov 2017
8. -- Description: Return all members
9. -- =============================================
10. --Store procedure name is --> stpGetAllMembers
11. CREATE PROCEDURE stpGetAllMembers
12. AS
13. BEGIN
14. -- SET NOCOUNT ON added to prevent extra result sets from
15. -- interfering with SELECT statements.
16. SET NOCOUNT ON;
17.
18. -- Select statements for procedure here
19. Select * from tblMembers
20. END
21. GO
Page 5 of 20
You should see a message, “Command(s) completed successfully.”
You can see in the following image, the new SP called stpGetAllMembers is created.
Page 6 of 20
Execute stored procedures in SQL Server
In below UI, right click on the SP name and select Execute Stored Procedure... to execute a SP. From here, you
can also modify an existing SP.
Now, we run our stored procedure called stpGetAllMembers. The output looks like the following:
Page 7 of 20
OUTPUT
Parameters in SPs are used to pass input values and return output values. There are two types of parameters:
Page 8 of 20
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.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author: Manoj Kalla
7. -- Create date: 20-Nov-2017
8. -- Description: Return specifc city records
9. -- =============================================
10. CREATE PROCEDURE stpGetMembersByCityName
11. -- Add the parameters for the stored procedure here
12. @CityName nvarchar(30)
13.
14. AS
15. BEGIN
16. -- SET NOCOUNT ON added to prevent extra result sets from
17. -- interfering with SELECT statements.
18. SET NOCOUNT ON;
19.
20. Select * From tblMembers
21. where MemberCity like '%'+@CityName+'%'
22.
23. END
24. GO
Execute it.
To run this SP, type the following command in SQL query tool:
EXEC GetMemberByCityName @CityName = 'mal'
OR from the UI, run the SP and provide the following input.
Page 9 of 20
The code to execute looks like the following:
1. USE [MBKTest]
2. GO
3.
4. DECLARE @return_value int
5.
6. EXEC @return_value = [dbo].[GetMemberByCityName]
7. @CityName = N'mal'
8.
9. SELECT 'Return Value' = @return_value
10.
11. GO
OUTPUT
Page 10 of 20
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.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author: Manoj Kalla
7. -- Create date: 20-Nov-2047
8. -- Description: To create a new member
9. -- =============================================
10. CREATE PROCEDURE stpInsertMember
11. @MemberName varchar(50),
12. @MemberCity varchar(25),
13. @MemberPhone varchar(15)
14.
15. AS
16. BEGIN
17. -- SET NOCOUNT ON added to prevent extra result sets from
18. -- interfering with SELECT statements.
19. SET NOCOUNT ON;
20.
21. Insert into tblMembers (MemberName,MemberCity,MemberPhone)
22. Values (@MemberName,@MemberCity, @MemberPhone)
23.
24. END
25. GO
Page 11 of 20
Pass the value of parameter in Execute dialog box. Something like this:
Page 12 of 20
The following code can be used to execute this SP in SSMS.
1. USE [MBKTest]
2. GO
3.
4. DECLARE @return_value int
5.
6. EXEC @return_value = [dbo].[stpInsertMember]
7. @MemberName = N'Mahesh Chand',
8. @MemberCity = N'NewYork',
9. @MemberPhone = N'9999945121'
10. SELECT 'Return Value' = @return_value
11. GO
OUTPUT
Page 13 of 20
In the query window, you can check if a new record for Member Name 'Mahesh Chand' is added to the table.
EXEC stpInsertMember @MemberName = 'Suhana & Ashish Kalla ', @MemberCity = 'Mumbai ',
@MemberPhone = N'9022592774xxx'
OUTPUT
You can check “Suhana & Ashish Kalla” record is added successfully.
Page 14 of 20
How to create an UPDATE quert based stored procedure?
Let's create a new SP that will update a table records based on the Member ID column. The ID is passed as an
input parameter. Here is the new SP that uses an UPDATE..SET..WHERE command.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author: Manoj Kalla
7. -- Create date: 20-Nov-2017
8. -- Description: Update a member detail by ID
9. -- =============================================
10. CREATE PROCEDURE stpUpdateMemberByID
11. @MemberID int,
12. @MemberName varchar(50),
13. @MemberCity varchar(25),
14. @MemberPhone varchar(15)
15.
16. AS
17. BEGIN
18. -- SET NOCOUNT ON added to prevent extra result sets from
19. -- interfering with SELECT statements.
20. SET NOCOUNT ON;
21.
22. UPDATE tblMembers
23. Set MemberName = @MemberName,
Page 15 of 20
24. MemberCity = @MemberCity,
25. MemberPhone = @MemberPhone
26. Where MemberID = @MemberID
27. END
28. GO
Right click on stored procedure in the Object Explorer and select Refresh. You will see the SP is created.
Now, Right click on SP name and select Execute stored procedure…. Provide the input values and execute.
1. USE [MBKTest]
Page 16 of 20
2. GO
3.
4. DECLARE @return_value int
5.
6. EXEC @return_value = [dbo].[stpUpdateMemberByID]
7. @MemberID = 20,
8. @MemberName = N'Nirupama Kalla',
9. @MemberCity = N'Mumbai',
10. @MemberPhone = N'904512541xxxx'
11.
12. SELECT 'Return Value' = @return_value
13.
14. GO
Let's create a SP that will delete records. The new SP uses a DELETE command and delete all records that
matches provided Member ID.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
Page 17 of 20
5. -- =============================================
6. -- Author: Manoj Kalla
7. -- Create date: 21-Nov-2017
8. -- Description: Delete a Member by Member ID
9. -- =============================================
10. CREATE PROCEDURE stpDeleteMemberByMemberID
11. @MemberID int
12. AS
13. BEGIN
14. -- SET NOCOUNT ON added to prevent extra result sets from
15. -- interfering with SELECT statements.
16. SET NOCOUNT ON;
17.
18. Delete from tblMembers
19. where MemberId = @MemberID
20.
21. END
22. GO
Execute it.
Right click on Stored Procedures in the Object Explorer and select Refresh.
Now again right click on stored procedure and select Execute stored procedure…
Page 18 of 20
RUN DELETE stored procedure BY MANUALLY (CODING)
EXEC stpDeleteMemberByMemberID 2
OUTPUT
You can see in image MemberID = 4 record has been deleted successfully.
Page 19 of 20
In this article, we saw how to create stored procedures in a SQL Server database for inserting, updating, and
deleting records.
Modifying the stored procedure
ALTER PROCEDURE GetProductDesc
AS
SELECT P.ProductID,P.ProductName,PD.ProductDescription FROM
Product P
INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductID
END
Renaming the stored procedure
sp_rename 'GetProductDesc','GetProductDesc_new'
Page 20 of 20