Saturday, 15 June 2013

how to write stored procedure in sql server

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 severl benefits of using a stored procedure and in those benefit  The main benefit , we get by using  stored procedure is that it increases the performance of the database.


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

 To  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
 
the above is the complete syntax of the store procedure 


Now we create a table 

CREATE TABLE  Students

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

the above table shows the initial index will start  with (1, 1)  as we  have used identity keyword


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:

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

Create  PROCEDURE sp_studentname(

@studentid INT                   --Input parameter    

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

 by default the parameter of the stored procedure is input , if we want parameter as output then we have to mention specificially  as OUTPUT

  /* 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 SP_GetstudentnameInOutputVariable
(

@studentid INT,                       --Input parameter 
@studentname VARCHAR(200)  OUT        -- Out parameter 
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname FROM Students 
                               WHERE studentid=@studentid
END
 
 


Alter  PROCEDURE GetstudentnameInOutputVariable
(

@studentid INT,                   --Input parameter  
@studentname VARCHAR (200) OUT,    -- Output parameter 
@StudentEmail VARCHAR (200)OUT     -- Output Parameter 
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname, 
    @StudentEmail=email FROM Students  
    WHERE studentid=@studentid;
END


 /*the below example of Stored procedure is used to Insert value into the table students.
*/

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

Execution of the Stored Procedure in SQL Server
Execution of the Stored Procedure which doesn'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 "Sp_Getstudentname", then we l use the following statement.

Execute Sp_Getstudentname 1
Exec Sp_Getstudentname 1



the above both are used to  execute the stored procedure







The  Below are the Advantages and Disadvantages of stored procedure 
Advantage of using Stored Procedure:

1:    Modular Programming: Stored procedures are modular. This is a good thing from a maintenance standpoint. When query trouble arises in your application, you would likely agree that it is much easier to troubleshoot a stored procedure than an embedded query buried within many lines of GUI code.
    
 2:   Function based access to tables: A user can have permissions to execute a stored procedure without having permission to operate directly on the underlying tables.
    
  3:  Reduced network traffic: Stored procedures   can consists of many individual SQL queries but can be executed with a single statement. This allows us to reduce the number and size of calls from the client to server.
    
  4:  Faster Execution: SP query plan are kept in memory after the first execution. The code doesn't have to be reparsed and repotimized on subsequent executions.

Disadvantage of using Stored Procedures

  1:  Increase in server processing requirement: Using stored procedures can increase the amount of server processing. In a large user environment with considerable activity in the server, it may be more desirable to offload some of the processing to the client side.
    
  2:  Business Logic in SP: Do not put all of your business logic into stored procedures. Maintenance and the agility of your application becomes an issue when you must modify business logic in T-SQL. For example, ISV applications that support multiple RDBMS should not need to maintain separate stored procedures for each system.








0 comments:

Post a Comment