Loading, please wait ...
Open its course - Database Systems Labs
Stored Procedures in SQL By Mukhtiar Zamin
Summary

Summary

4
Teachers with
Mukhtiar Zamin
19
Followers
For Learning
All
Visibility
Security Status
4
Contributions
By Teachers
Notes
  1. Students are auto-evaluated against related topics to ensure they learned it.

This lab introduce students to stored procedures, their use and some examples such that user should be able to write them for their semester projects where necessary

Objectives

This lab introduces the stored procedures and discuss several examples of how effectively can we use stored procedures. Also make students learn how to pass parameters to stored procedures.

Scope

  • Creating Stored Procedures
  • Using Stored Procedures
  • Passing parameters to stored procedures

What is a Stored Procedure?

A procedure that you write in SQL to replace writing some reusable queries again and again such that results can be filtered with parameters. Instead of calling multiple statements from your application you can call the stored procedure to do a batch of work with just one statement.

Stored Procedure Common Syntax in SQL Server for All, By Mukhtiar Zamin

Common Syntax in SQL

In SQL Server Management Studio you can define a new one by right-click on "Stored Procedures" under "Programmability" and click on Stored Procedure to open default template:

-- =============================================
-- Author:		
-- Create date: 
-- Description:	
-- =============================================
CREATE PROCEDURE  
	-- Add the parameters for the stored procedure here
	<@Param1, sysname, @p1>  = , 
	<@Param2, sysname, @p2>  = 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
END
GO

Local And Global Temporary Tables in SQL Server for All, By Mukhtiar Zamin

Points to remember

  1. Temp tables are created in TempDB database and are automatically deleted, when they are no longer used.
  2. There are 2 types of temporary tables
  3. The first type "Local Temp tables" are prefixed with single pound (#) symbol. The second type "Global temp tables are prefixed with 2 pound (##) symbols.
  4. Examples on: www.c-sharpcorner.com

Basic Examples for All, By Mukhtiar Zamin

Example 1 - simple stored procedure

Create a stored procedure to get the last added employee.

CREATE PROCEDURE  getLastEmployee
AS
BEGIN
	SELECT TOP 1 *  FROM [northwindd].[dbo].[Employees] order by EmployeeID desc
END
GO
To run it use:
EXEC getLastEmployee

Example 2 - stored procedure with a parameter

Create a stored procedure to get employee by FirstName.

CREATE PROCEDURE  getEmployeeByFirstName
@LastName NVARCHAR(50) 
AS
BEGIN
	SELECT *  FROM [northwindd].[dbo].[Employees] where FirstName=@LastName;
END
GO
To run it use:
EXEC getEmployeeByFirstName 'Ali'
or
EXEC getEmployeeByFirstName @LastName='Ali'

Example 3 - stored procedure with a parameter and output parameter

Create a stored procedure to get employee id who process the last order in a given year.

CREATE PROCEDURE  getEmployeeIDWithMostOrdersByYear
@YearDate NVARCHAR(4),
@EmployeeId INT output 
AS
BEGIN
  
  SELECT TOP 1 @EmployeeId = [EmployeeID]
  FROM [northwindd].[dbo].[Orders]
  GROUP By EmployeeID, OrderDate
  having YEAR(OrderDate) = @YearDate
  order by OrderDate desc

END
GO
To run it use:
DECLARE @EmployeeID INT 
SET @EmployeeID = 0 
EXEC getEmployeeIDWithMostOrdersByYear @YearDate ='1997', @EmployeeID =@EmployeeId OUTPUT 
SELECT @EmployeeID as EmployeeID

Northwind Stored Procedures for All, By Mukhtiar Zamin

Northwind database has already a number of stored procedures. Try to understand them, execute them and write similar stored procedures for your semester project.

  1. Customers By City
    ALTER PROCEDURE [dbo].[Customers By City]
    	-- Add the parameters for the stored procedure here
    	(@param1 NVARCHAR(20), @order bit)
    AS
    BEGIN
    	-- SET NOCOUNT ON added to prevent extra result sets from
    	-- interfering with SELECT statements.
    	SET NOCOUNT ON;
    	if(@order = 0)
    	BEGIN
    		SELECT CustomerID, ContactName, CompanyName, City from Customers as c where c.City=@param1
    	END
    	else
    	BEGIN
    	SELECT CustomerID, ContactName, CompanyName, City from Customers as c where c.City=@param1 order by CustomerID desc
    	END
    END
    
  2. Customers Count By Region
    ALTER PROCEDURE [dbo].[Customers Count By Region]
    	-- Add the parameters for the stored procedure here
    	(@param1 NVARCHAR(15))
    AS
    BEGIN
    	-- SET NOCOUNT ON added to prevent extra result sets from
    	-- interfering with SELECT statements.
    	SET NOCOUNT ON;
    	DECLARE @count int
    	SELECT @count = COUNT(*)FROM Customers WHERE Customers.Region = @Param1
    	RETURN @count
    END
    
  3. Customer Order History
    ALTER PROCEDURE [dbo].[CustOrderHist] @CustomerID nchar(5)
    AS
    SELECT ProductName, Total=SUM(Quantity)
    FROM Products P, [Order Details] OD, Orders O, Customers C
    WHERE C.CustomerID = @CustomerID
    AND C.CustomerID = O.CustomerID AND O.OrderID = OD.OrderID AND OD.ProductID = P.ProductID
    GROUP BY ProductName
    
  4. Customer Orders Detail
    ALTER PROCEDURE [dbo].[CustOrdersDetail] @OrderID int
    AS
    SELECT ProductName,
        UnitPrice=ROUND(Od.UnitPrice, 2),
        Quantity,
        Discount=CONVERT(int, Discount * 100), 
        ExtendedPrice=ROUND(CONVERT(money, Quantity * (1 - Discount) * Od.UnitPrice), 2)
    FROM Products P, [Order Details] Od
    WHERE Od.ProductID = P.ProductID and Od.OrderID = @OrderID
    

×

Stored Procedures in SQL Evaluation

To earn PASS status, system is about to evaluate you using multiple choice questions (MCQs) and True/False type questions.

  • CAREFULLY READ THE FOLLOWING INSTRUCTIONS!
  • Make sure you have learned this lecture along with its topics and tutorials.
  • On first evaluation you get 100% marks on correct answer, then on 2nd you get 95% marks and so on.
  • Answer the questions with a gap NOT MORE THAN A MINUTE, Otherwise it will re-start.

I have read above instrucitons and ready for evaluation.
Your's
Status
Not Registered
Teacher
Mukhtiar Zamin
Alert
Your performance monitoring will start when you register in a class of this course.

Questions on

Contact Us

support@subexpert.com
Write to Us View Help
Subject Expert Logo

Subject Expert

Learn, Evaluate and Optimize

Follow Us
Facebook Switch Display Mode Enable Translation
© 2024 - Subject Expert