Stored Procedure With Real Time Scenario In SQL Server

In this blog, I am going to explain, how to create a procedure in the real time scenario.

What is a procedure:

A stored procedure is a set of SQL statements, which has been created and stored in the database as an object. Stored procedure will accept the input and output parameters, so that a single procedure can be used over the network by several users, using different input. Stored procedure will reduce the network traffic and increase the performance.

Real time scenario

Step 1: Create a table to describe and create the stored procedure.

  1. create table Product  
  2. (  
  3.       ProductId int primary key,  
  4.       ProductName varchar(20) unique,  
  5.       ProductQty int,  
  6.       ProductPrice float  
  7. )  

Step 2: Insert some value to the describe scenario.

  1. insert product values(1,'Printer',10,4500)  
  2. insert product values(2,'Scanner',15,3500)  
  3. insert product values(3,'Mouse',45,500)   

Step 3: Check your table with the inserted value.

  1. select * from product   

Step 4: Real time scenario is given below:

Create a stored procedure, which is used to perform the requirements, given below:
  1. Before inserting, check the detail about the product name. If the product name is available, update an existing product qty + inserted product qty,
  2. Before inserting, check the detail about the product name. If the product name is available, check the product price. If the existing product price is less, the inserted product product price replaces the existing product price with the inserted product price.
  3. If first and second conditions are not satisfied, insert the product information, as new record into the table.

  1. create procedure prcInsert   
  2. @id int,  
  3. @name varchar(40),  
  4. @qty int,  
  5. @price float  
  6. as  
  7. begin  
  8.  declare @cnt int  
  9.  declare @p float  
  10.  select @cnt=COUNT(ProductId)from Product where pname=@name  
  11.  if(@cnt>0)  
  12.  begin  
  13.   update Product set ProductQty=ProductQty+@qty where ProductName=@name  
  14.   select @p=ProductPrice from Product where ProductName=@name  
  15.   if(@p<@price)  
  16.   begin  
  17.    update Product set ProductPrice=@price where ProductName=@name  
  18.   end  
  19.  end  
  20.  else  
  21.  begin  
  22.   insert Product values(@id,@name,@qty,@price)  
  23.  end  
  24. end   

That's it. Thank you. If any suggestion or clarification is required, kindly revert back with the comments. 

Ebook Download
View all
Learn
View all