Click here to Skip to main content
Click here to Skip to main content

Sql Server - How to write a Stored procedure in Sql server

By , 12 Nov 2010
 

Stored Procedure:- Stored Procedure In Sql server can be defined as the set of logically group of sql statement which are grouped to perform a specific task. There are many benefits of using a stored procedure. The main benefit of using a stored procedure is that it increases the performance of the database.The other benefits of using the Stored Procedure is given below:-

Benefits of using the Stored Procedure

  1. One of the main benefit of using the Stored procedure is that it reduces the amount of information sent to the database server. It can become more important benefit when the bandwidth of the network is less. Since if we send the sql query (statement)which is executing in a loop to the server through network and the network get disconnected then the execution of the sql statement don't returns the expected results, if the sql query is not used between Transaction statement and rollback statement is not used.
  2. Compilation step is required only once when the stored procedure is created. Then after it does not required recompilation before executing unless it is modified and re utilizes the same execution plan whereas the sql statements needs to be compiled every time whenever it is sent for execution even if we send the same sql statement every time.
  3. It helps in re usability of the sql code because it can be used by multiple users and by multiple client since we needs to just call the stored procedure instead of writing the same sql statement every time. It helps in reduces the development time.
  4. Stored procedure is helpful in enhancing the security since we can grant permission to the user for executing the Stored procedure instead of giving the permission on the tables used in the Stored procedure.
  5. Sometime it is useful to use the database for storing the business logic in the form of stored procedure since it make it secure and if any change is needed in the business logic then we may only need to make changes in the stored procedure and not in the files contained on the web server.

How to write a Stored Procedure in SQL Server

Suppose there is a table called tbl_Students whose structure is given below:

CREATE TABLE  tbl_Students

(
    [Studentid] [int] IDENTITY(1,1) NOT NULL,
    [Firstname] [nvarchar](200) NOT  NULL,
    [Lastname] [nvarchar](200)  NULL,
    [Email] [nvarchar](100)  NULL
)

Support we insert the following data into the above table:-

Insert into tbl_Students (Firstname, lastname, Email)
 Values('Vivek', 'Johari', 'vivek@abc.com')

Insert into tbl_Students (Firstname, lastname, Email)
 Values('Pankaj', 'Kumar', 'pankaj@abc.com')

Insert into tbl_Students (Firstname, lastname, Email)
 Values('Amit', 'Singh', 'amit@abc.com')

Insert into tbl_Students (Firstname, lastname, Email)
 Values('Manish', 'Kumar', 'manish@abc.comm')

Insert into tbl_Students (Firstname, lastname, Email)
 Values('Abhishek', 'Singh', 'abhishek@abc.com')

Now, while writing a Stored Procedure, the first step will be to write the Create Procedure statement as the first statement,

Create Procedure Procedure-name 
(
Input parameters ,
Output Parameters (If required)
)
As
Begin
     Sql statement used in the stored procedure
End

Now, suppose we need to create a Stored Procedure which will returns a student name whose studentid is given as the input parameter to the stored procedure. Then the Stored Procedure will be:-

/*  Getstudentname is the name of the stored procedure*/

Create  PROCEDURE Getstudentname(

@studentid INT                   --Input parameter ,  Studentid of the student 

)
AS
BEGIN
SELECT Firstname+' '+Lastname FROM tbl_Students WHERE studentid=@studentid 
END

We can also collect the student name in the output parameter of the Stored Procedure.For Example:

 /* 
GetstudentnameInOutputVariable is the name of the stored procedure which
uses output variable @Studentname to collect the student name returns by the
stored procedure
*/

Create  PROCEDURE GetstudentnameInOutputVariable
(

@studentid INT,                       --Input parameter ,  Studentid of the student
@studentname VARCHAR(200)  OUT        -- Out parameter declared with the help of OUT keyword
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname FROM tbl_Students WHERE studentid=@studentid
END

Note:-/* */ is used to write comments in one or multiple lines

-- is used to write comment in a single line

How to Alter a Stored Procedure in a Sql server:-

In SQL Server, a stored procedure can be modified with the help of the Alter keyword.Now if, we want to get student email address through the same procedure GetstudentnameInOutputVariable . So we need to modified it by adding one more output parameter " @StudentEmail " which is shown below:

/* 
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/

 

Alter  PROCEDURE GetstudentnameInOutputVariable
(

@studentid INT,                   --Input parameter ,  Studentid of the student
@studentname VARCHAR (200) OUT,    -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT     -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname, 
    @StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END

Note: It is not necessary that a stored procedure will have to written. It can be the case when a stored procedure doesn't written any thing. For Example, a stored procedure can be used to Insert, delete or update a sql statement. For Example the below stored procedure is used tp insert value into the table tbl_students.

/*
This Stored procedure is used to Insert value into the table tbl_students. 
*/

Create Procedure InsertStudentrecord
(
 @StudentFirstName Varchar(200),
 @StudentLastName  Varchar(200),
 @StudentEmail     Varchar(50)
) 
As
 Begin
   Insert into tbl_Students (Firstname, lastname, Email)
   Values(@StudentFirstName, @StudentLastName,@StudentEmail)
 End

Execution of the Stored Procedure in SQL Server

Execution of the Stored Procedure which don't have a Output Parameter

A stored procedure is used in the Sql server with the help of the "Execute" or "Exec" Keyword. For Example, If we want to execute the stored procedure "Getstudentname", then we will use the following statement.

Execute Getstudentname 1
Exec Getstudentname 1

Execution of the Stored Procedure using the Output Parameter

If we want to execute the Stored procedure "GetstudentnameInOutputVariable " , then we first need to declare the variable to collect the output values. For example

Declare @Studentname as nvarchar(200)   -- Declaring the variable to collect the Studentname
Declare @Studentemail as nvarchar(50)     -- Declaring the variable to collect the Studentemail
Execute GetstudentnameInOutputVariable 1 , @Studentname output, @Studentemail output
select @Studentname,@Studentemail      -- "Select" Statement is used to show the output from Procedure

Summary

In the end we can say that a Stored procedure not only enhancing the possibility of reusing the code and execution plan, but it also increases the performance of the database by reducing the traffic of the network by reducing the amount of information send over the network.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Vivek Johari
Software Developer (Senior) Magic Software Pvt Ltd
India India
Member
I am currently working as a Analyst and have around 6 yeras of experience in database.Currently, I am working in Magic Software Pvt.Ltd. in Noida.
 
Degree:-
Master Degree in Computer(MCA)
 
Work experience:-
Designing of the database.
Database Optimization.
Writing Complex Stored Procedures,Functions,Triggers etc.
Designing and developing SSIS & DTS packages.
Designing SQL Reports using SSRS.
Database Server Maintenance.
 
Certification:-
Microsoft certified Sql DBA in Sql server 2008 (MCTS).
Microsoft certified BI professional in Sql server 2008 (MCTS).
Oracle certified profession DBA in ORACLE 10g (OCP)
certified profession DBA in ORACLE 9i (OCP)
 
My other publication
Technical Blog:- Technologies with Vivek Johari
 
Moderator and Blogger at BeyondRelational.com
 
Guest Author and Blogger at sqlservercentral.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionPrecise & Absolute:)memberVick_Web21 Mar '13 - 20:19 
Superb to clear the basis concepts. really helpful.
GeneralMy vote of 5memberDecoyer24 Jan '13 - 4:33 
For a beginner, this is a good start.
QuestiontksmemberBobby43628 Dec '12 - 6:29 
tis one truely helpful to me
QuestionMy vote of 5memberchandu G29 Nov '12 - 18:48 
Nice one for beginners
GeneralMy vote of 5memberchandu G29 Nov '12 - 18:47 
Nice article for beginners
GeneralMy vote of 3memberArpan Guin22 Oct '12 - 4:28 
good explanation
GeneralMy vote of 5membergramesh.hi8 Oct '12 - 3:37 
GOOD EXPLANATION
QuestionHow to Fetch the data from multiple tables using Linq in MVPmemberNeena Panicker23 Aug '12 - 0:24 
I am working in Silverlight C#-- MVP. I have 5 tables and wants to fetch data from that tables with LINQ query.

my TABLES are as below...

1)aspnet_UsersInRole

Field
______________

UserId (PK,FK)
RloeId (PK,FK)

2)aspnet_Users

Field
_____________

ApplicationId (FK uniqueidentifier Unchecked
UserId (PK uniqueidentifier Unchecked
UserName nvarchar(256) Unchecked
LoweredUserName nvarchar(256) Unchecked
MobileAlias nvarchar(16) Checked
IsAnonymous bit Unchecked
LastActivityDate datetime Unchecked

3)CompanyRole

Fields
_________

CompanyRoleID (PK bigint Unchecked
CompanyID (FK bigint Checked
RoleID (FK uniqueidentifier Checked


4)Company

Fields
___________

CompanyID (PK bigint Unchecked
Name nvarchar(500) Checked
Address nvarchar(200) Checked
City nvarchar(50) Checked
Zip nvarchar(50) Checked
ContactName nvarchar(500) Checked
Phone nvarchar(50) Checked
Fax nvarchar(50) Checked
Email nvarchar(500) Checked
LogoImage nvarchar(50) Checked
IsActive bit Checked

5)aspnet_Roles
_____________________

ApplicationId (FK uniqueidentifier Unchecked
RoleId (PK uniqueidentifier Unchecked
RoleName nvarchar(256) Unchecked
LoweredRoleName nvarchar(256) Unchecked
Description nvarchar(256) Checked

Now i want to get data
(using LINQ Query)

1)Name

So,How can to fetch data with linq query?
QuestionJoins and stored proceduresmemberBiodude Basava20 Jul '12 - 21:54 
I have these Data:-
 
----------------------- 1 ---------------------------------------------------------
 
select Com.CountryName+', '+Cm.CityName+', '+Fac.FacilityName+', '+FM.FloorCode as Details
 
from MC_MeetingRoom_Master MR join MC_Floor_Master FM on MR.FloorID=FM.FloorID AND FM.IsActive=1
 
JOIN MC_Building_Master BM on BM.BuildingID=FM.BuildingID AND BM.IsActive=1
 
JOIN MC_Facility_Master Fac on BM.FacilityID=Fac.FacilityID and Fac.IsActive=1
 
join MC_City_Master Cm on Fac.CityID = Cm.CityID and Cm.IsActive=1
 
join MC_Country_Master Com on Cm.CountryID=Com.CountryID and Com.IsActive=1
 
WHERE MeetingRoomID=1000
 

The above query shows:-
 
India, Chennai, CHN - DLF Infocity - SEZ, 3rd Floor
 
-------------------------- 2 -------------------------------------------------------------
 

Another table where
 
select [MeetingRoomID],[Capacity],[MeetingRoomVNET], CASE WHEN [HasProjector] =0 then 'No' ELSE 'Yes' END [HasProjector],CASE WHEN [HasLan]=0 then 'No' ELSE 'Yes' END [HasLan],CASE WHEN [HasComputer]=0 then 'No' ELSE 'Yes' END [HasComputer],CASE WHEN [HasWhiteBoard]=0 then 'No' ELSE 'Yes' END [HasWhiteBoard],[MeetingRoomAdminMail]
 
from MC_MeetingRoom_Master where [MeetingRoomID]=1023
 
The above query shows columns:-
 
1023 25 0 No No No No Admin.Helpdesk@cognizant.com
 
-------------------------------------------------------------------------------------------
 
But i wanted to join both the queries...??
 
Do i need to create stored procedures..??
GeneralMy vote of 5memberMember 84804019 Jul '12 - 18:37 
This post gave me a good knowledge in stored procedures
GeneralRe: My vote of 5memberVivek Johari10 Jul '12 - 7:39 
Thanks
GeneralMy Vote 5memberSanti Santosh Mahapatra2 Jul '12 - 18:59 
Its very good for any body to learn how to write procedure. Hats off
GeneralRe: My Vote 5memberVivek Johari9 Jul '12 - 7:58 
ThanksSmile | :)
GeneralRe: My Vote 5memberraendra24 Aug '12 - 2:50 
It is good
GeneralMy vote of 5membernikhil _singh26 Jun '12 - 0:12 
Really Helpful article. Lot of Developers Don't know these things .even i was one of them before Reading this Article.
GeneralRe: My vote of 5memberVivek Johari26 Jun '12 - 5:56 
Thanks Nikhil for your valuable feedback..Smile | :)
Vivek Johari
www.vivekjohari.blogspot.com

SuggestionNicememberGNWebSoft26 Feb '12 - 3:03 
Really nice article for beginners.
 
But I like to add that most of CRUD Stored Procedures are Typical and they can be generated automatically like Tools4sql.net's Stored Procedure Generator.
GeneralRe: NicememberVivek Johari26 Jun '12 - 5:54 
ThanksSmile | :)
GeneralNice outline of benefitsmemberPractability.com16 Nov '10 - 23:54 
It's easy to forget that stored procedures reduce the data transfer requests; I know there are times I forget to uses SP simply because high speed internet access has me spoiled.
GeneralRe: Nice outline of benefitsmemberVivek Johari17 Nov '10 - 0:22 
Thanks......
Generalabout the out in parametermembersudan prajapati15 Nov '10 - 7:07 
hi
 
my name is sudon and i am new in stored procedure section thanks for the article but i am little bit confuse how to use the out parameter
 
for eg.
 
create procedure change(
@int id
@name nvarchar(50)out/* i need this data to be shown but i didn' understand how to get this data using exec*/
 
)
as
begin
select * from student where id=@id
end
 
thanks in advance
GeneralRe: about the out in parametermemberVivek Johari17 Nov '10 - 5:30 
Hi Sudan,
Sorry for replying late.
If I understand your problem correctly, you want to get the @name as the output value but when you execute this procedure it returns Null. It happen since the query "select * from student where id=@id" return all the columns from the table student and Sql Server get confused to which column's value should be assign to the variable @name.
I try to give you solution through this procedure:-
 
Create procedure change(
@id int,
@name nvarchar(50)out/* i need this data to be shown but i didn' understand how to get this data using exec*/
 
)
as
begin
select @name=[Firstname] from tbl_Students where [Studentid]=@id
end
 
Here I used the table used in the above article. In this procedure, I assign the value of the name column to the variable @name. When I execute this procedure, it gives the name of the student whose studentid is ggiven as an input.
 
Query for executing the above Stored Procedure:-
Declare @name as nvarchar(200)
Execute change 1 , @name output
select @name
 
Hope this answer will clear your confusion http://s.codeproject.com/script/Forums/Images/smiley_smile.gif
Vivek Johari
Engineer Analyst
Magic Software Pvt. Ltd.
INDIA

GeneralMy vote of 5memberSlacker00715 Nov '10 - 0:23 
Thanks!! 5
GeneralRe: My vote of 5memberVivek Johari15 Nov '10 - 5:16 
Thanks......... Smile | :)
GeneralGood Post.memberHiren Solanki12 Nov '10 - 17:11 
Though this is very much for beginners, but for me the Benefit of using stored. proc was useful for me,
 
Take a 5 !!
Rating is Always appreciated.
Regards,
Hiren Solanki.
Indian Forum | My Articles | My Profile
"You will always find me near 127.0.0.1"

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 12 Nov 2010
Article Copyright 2010 by Vivek Johari
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid