Saturday 23 September 2017

Sql Server - How To Write a Stored Procedure in SQL Server

Stored Procedure: Stored Procedure in SQL Server can be defined as the set of logical group of SQL statements 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 are given below.

Benefits of Using the Stored Procedure

  1. One of the main benefits of using the Stored procedure is that it reduces the amount of information sent to the database server. It can become a 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 gets disconnected, then the execution of the SQL statement doesn't return 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 require recompilation before executing unless it is modified and reutilizes the same execution plan whereas the SQL statements need 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 clients since we need to just call the stored procedure instead of writing the same SQL statement every time. It helps in reducing 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 permission on the tables used in the Stored procedure.
  5. Sometimes, it is useful to use the database for storing the business logic in the form of stored procedure since it makes 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

  1. Simple Procedure
  2. With parament
  3. Optional Parameter
  • Simple store Procedure
Create Procedure SpGetEmployeeList
as
begin
select name, gender, salary from tblEmployee
end 


  • With parameter store Procedure
Create Procedure SpGetEmployeeList
@name nvarchar(100),
@gender nvarchar(10),
@Salary decimal(18,2)
as
begin
insert into tbl_employee(name, gender, salary)
values(@name, @gender, @salary)
end 


  • Optional parameter Store Procedure
Create Procedure SpGetEmployeeList
@name nvarchar(100),
@gender nvarchar(10),
@Salary decimal(18,2) = null
as
begin
insert into tbl_employee(name, gender, salary)
values(@name, @gender, @salary)
end 





No comments:

Post a Comment