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

, 12 Nov 2010
Rate this:
Please Sign up or sign in to vote.
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. This article will describe the Stored Procedure in Sql server and their benefits

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)

Share

About the Author

Vivek Johari
Technical Lead
India India
I am currently working as a Analyst and have around 7.5 years of experience in database.
 
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
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
SuggestionThis extremely simplistic useless article PinmemberPokemonCraft24-Aug-14 13:55 
GeneralMethods of Writing Appllication PinmemberMember 109771611-Aug-14 4:27 
GeneralRe: Methods of Writing Appllication Pinmvp Akhil Mittal 3-Aug-14 23:17 
QuestionUse of Output parameters PinprofessionalAjay Shedge21-Jul-14 2:15 
Questionoutput parameter with WITH PinmemberMember 1094936515-Jul-14 18:48 
General-- PinmemberMember 1090459810-Jul-14 0:54 
Questioncreating a summarized report in MS SQL Stored Procedure PinmemberMember 109280446-Jul-14 13:29 
GeneralTHANK YOU - BEST ARTICLE EVER PinmemberAnkit Mishra28-Jun-14 0:41 
GeneralRe: THANK YOU - BEST ARTICLE EVER PinmemberVivek Johari1-Jul-14 20:19 
GeneralExcellent Article! Pingrouprkrockr18-Jun-14 19:45 
GeneralRe: Excellent Article! PinmemberVivek Johari1-Jul-14 20:19 
QuestionSum of No of Hours PinmemberPriyant Jain29-Apr-14 22:30 
QuestionDOUBT [modified] Pinmembergnana11926-Mar-14 19:22 
QuestionBest One !! PinmemberGaganbhatia2-Mar-14 5:45 
AnswerRe: Best One !! PinmemberVivek Johari13-Mar-14 17:34 
QuestionRegarding SQL PinmemberMember 1062802426-Feb-14 7:31 
AnswerRe: Regarding SQL PinmemberVivek Johari13-Mar-14 17:33 
GeneralNice Code PinmemberPatil Kishor30-Nov-13 4:38 
GeneralRe: Nice Code PinmemberVivek Johari30-Nov-13 21:21 
GeneralSimple and clear Pinmemberkarthik cad/cam24-Oct-13 22:02 
GeneralRe: Simple and clear PinprofessionalPaulo Augusto Künzel30-Oct-13 2:31 
GeneralRe: Simple and clear PinmemberVivek Johari30-Nov-13 21:20 
GeneralRe: Simple and clear PinmemberVivek Johari30-Nov-13 21:21 
GeneralMy vote of 4 PinprofessionalT.Vamshi krishna Reddy28-Aug-13 19:42 
GeneralRe: My vote of 4 PinmemberVivek Johari9-Sep-13 1:31 
Generalvery nice PinmemberAijaz44412-Aug-13 7:11 
GeneralRe: very nice PinmemberVivek Johari9-Sep-13 1:35 
QuestionPrecise & Absolute:) PinmemberVick_Web21-Mar-13 20:19 
AnswerRe: Precise & Absolute:) PinmemberVivek Johari9-Sep-13 1:42 
GeneralMy vote of 5 PinmemberDecoyer24-Jan-13 4:33 
GeneralRe: My vote of 5 PinmemberVivek Johari9-Sep-13 1:43 
Questiontks PinmemberBobby43628-Dec-12 6:29 
tis one truely helpful to me
AnswerRe: tks PinmemberVivek Johari9-Sep-13 1:42 
QuestionMy vote of 5 Pinmemberchandu G29-Nov-12 18:48 
AnswerRe: My vote of 5 PinmemberVivek Johari9-Sep-13 1:43 
GeneralMy vote of 5 Pinmemberchandu G29-Nov-12 18:47 
GeneralRe: My vote of 5 PinmemberVivek Johari9-Sep-13 1:43 
GeneralMy vote of 3 PinmemberArpan Guin22-Oct-12 4:28 
GeneralRe: My vote of 3 PinmemberVivek Johari9-Sep-13 1:35 
GeneralMy vote of 5 Pinmembergramesh.hi8-Oct-12 3:37 
GeneralRe: My vote of 5 PinmemberVivek Johari9-Sep-13 1:31 
QuestionHow to Fetch the data from multiple tables using Linq in MVP PinmemberNeena Panicker23-Aug-12 0:24 
QuestionJoins and stored procedures PinmemberBiodude Basava20-Jul-12 21:54 
GeneralMy vote of 5 PinmemberMember 84804019-Jul-12 18:37 
GeneralRe: My vote of 5 PinmemberVivek Johari10-Jul-12 7:39 
GeneralMy Vote 5 PinmemberSanti Santosh Mahapatra2-Jul-12 18:59 
GeneralRe: My Vote 5 PinmemberVivek Johari9-Jul-12 7:58 
GeneralRe: My Vote 5 Pinmemberraendra24-Aug-12 2:50 
GeneralMy vote of 5 Pinmembernikhil _singh26-Jun-12 0:12 
GeneralRe: My vote of 5 PinmemberVivek Johari26-Jun-12 5:56 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140826.1 | Last Updated 12 Nov 2010
Article Copyright 2010 by Vivek Johari
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid