0% found this document useful (0 votes)
21 views36 pages

Stored Procedure Activity

This document discusses stored procedures in SQL databases. Stored procedures allow grouping SQL statements and logic into reusable code modules. They provide benefits like improved performance, modularity, security and reduced network traffic. The document also provides examples of creating stored procedures to retrieve employee data by department and get totals by customer or product.

Uploaded by

John Ivan Maurat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views36 pages

Stored Procedure Activity

This document discusses stored procedures in SQL databases. Stored procedures allow grouping SQL statements and logic into reusable code modules. They provide benefits like improved performance, modularity, security and reduced network traffic. The document also provides examples of creating stored procedures to retrieve employee data by department and get totals by customer or product.

Uploaded by

John Ivan Maurat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

STORED PROCEDURE

STORED PROCEDURE
• A stored procedure is a precompiled collection of SQL statements and procedural
logic that is stored in the database and can be executed on demand.
• It's essentially a reusable and organized set of SQL commands that perform a specific
task or set of tasks.
• Stored procedures are widely used in database management systems like SQL Server,
MySQL, Oracle, etc.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 2


CHARACTERISTICS AND BENEFITS OF STORED PROCEDURES:
1. Modularity and Reusability: Stored procedures allow you to modularize your SQL code.
You can create a procedure once and reuse it multiple times in your application without
having to rewrite the same SQL logic each time.
2. Reduced Network Traffic: Because stored procedures are executed on the database server
itself, they can reduce the amount of data transferred between the client and the server.
This can lead to improved performance, especially for complex operations.
3. Improved Performance: Stored procedures are precompiled and optimized by the
database engine, which can result in faster execution compared to executing individual SQL
statements separately.
4. Security: Stored procedures can help enforce security by allowing fine-grained control over
database access. You can grant execute permissions on specific procedures to users or
roles, limiting their ability to directly access tables or modify data.
5. Transaction Management: Stored procedures can be used to encapsulate multiple SQL
statements within a single transaction, ensuring data consistency and integrity.
6. Encapsulation of Business Logic: You can encapsulate complex business logic within stored
procedures, making it easier to maintain and manage your application's functionality.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 3


STORED PROCEDURE CONCEPTS
DISCUSSION (Q&A)

1. What is a stored procedure in SQL?


A) A temporary table used for storing intermediate results
B) A collection of SQL statements and procedural logic stored on the server
C) A type of database index used for improving query performance
D) A table-valued function used for data transformation

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 4


STORED PROCEDURE CONCEPTS
DISCUSSION (Q&A)

2. Which of the following is a benefit of using stored procedures?


A) Increased network traffic
B) Reduced database security
C) Improved performance by reducing round trips to the server
D) Limited modularity and reusability of code

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 5


STORED PROCEDURE CONCEPTS
DISCUSSION (Q&A)

3. Which SQL command is used to create a stored procedure?


A) CREATE PROCEDURE
B) B) INSERT INTO
C) C) SELECT
D) D) UPDATE

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 6


STORED PROCEDURE CONCEPTS
DISCUSSION (Q&A)

4. What does the following stored procedure do?

A) Inserts a new customer record into the Customers table


B) Retrieves a customer's details based on their ID
C) Deletes a customer record from the Customers table
D) Updates a customer's information in the Customers table

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 7


STORED PROCEDURE CONCEPTS
DISCUSSION (Q&A)

5. What is the advantage of using stored procedures for database


operations?

A) They increase network traffic.


B) They improve security by exposing SQL code to users.
C) They reduce the need for writing SQL queries in application code.
D) They limit the ability to reuse code across multiple applications.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 8


STORED PROCEDURE CONCEPTS
DISCUSSION (Q&A)

ANSWERS
1. B) A collection of SQL statements and procedural logic stored on the
server.
2. C) Improved performance by reducing round trips to the server.
3. A) CREATE PROCEDURE
4. B) Retrieves a customer's details based on their ID.
5. C) They reduce the need for writing SQL queries in application code.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 9


CREATE A STORED PROCEDURE TO GET
EMPLOYEE DETAILS BY DEPARTMENT
CREATE PROCEDURE GetEmployeesByDepartment This stored procedure is named
@DepartmentName NVARCHAR(50) GetEmployeesByDepartment and takes one
AS input parameter @DepartmentName of type
BEGIN NVARCHAR(50).
SELECT
Inside the procedure, it uses a SELECT
statement to retrieve employee details (first
E.FirstName,
name, last name) along with the department
E.LastName, name for employees belonging to the
D.DepartmentName specified department.
FROM
Employees E To execute this stored procedure in SSMS:
INNER JOIN 1.Open SQL Server Management Studio.
2.Connect to your SQL Server instance.
Departments D ON E.DepartmentID = D.ID
3.Open a new query window.
WHERE 4.Paste the code above into the query
D.DepartmentName = @DepartmentName; window.
END; 5.Execute the code (either by pressing F5 or
clicking the "Execute" button).

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 10


GETEMPLOYEESBYDEPARTMENT
• After executing the code, the stored procedure GetEmployeesByDepartment will
be created in your database.
• You can then execute the stored procedure by providing a department name as the
input parameter to retrieve employee details for that department. For example:

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 11


CREATE TABLE
• Create a simple sample database schema with two tables: Employees and Departments.
• Populate these tables with some sample data to demonstrate a stored procedure that
retrieves employee details based on the department.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 12


HERE'S THE SQL SCRIPT TO CREATE THE SAMPLE TABLES AND INSERT
SOME DATA:

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 13


CREATE A STORED PROCEDURE NAMED GETEMPLOYEESBYDEPARTMENT
TO RETRIEVE EMPLOYEE DETAILS BASED ON A SPECIFIED DEPARTMENT:

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 14


PRACTICE STORED PROCEDURE
Create the following table:

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 15


PRACTICE STORED PROCEDURE
Populate the tables:

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 16


CREATE A STORED PROCEDURE TO GET TOTAL
ORDER AMOUNT FOR EACH CUSTOMER

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 17


CREATE A STORED PROCEDURE TO GET THE
TOTAL NUMBER OF ORDERS PER CUSTOMER

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 18


EXPLANATION
In this stored procedure:
• We use a LEFT JOIN between the Customers and Orders tables to include all
customers, even if they haven't placed any orders.
• The COUNT(O.OrderID) function is used to count the number of orders for each
customer.
• The result set includes columns CustomerName (concatenated first and last names)
and TotalOrders.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 19


CREATE A STORED PROCEDURE TO GET THE
TOTAL SALES AMOUNT PER PRODUCT

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 20


EXPLANATION
In this stored procedure:
• We use a LEFT JOIN between the Products and Orders tables to include all products,
even if they haven't been ordered.
• The SUM(P.UnitPrice * O.Quantity) expression calculates the total sales amount for
each product by multiplying the unit price of the product by the quantity ordered
and then summing those values.
• The result set includes columns ProductName and TotalSalesAmount.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 21


ACTIVITY: ORDER PROCESSING
Objective:
Create a stored procedure to process new orders in a fictional online store.
Tables:
1. Customers (CustomerID, FirstName, LastName, Email)
2. Products (ProductID, ProductName, UnitPrice)
3. Orders (OrderID, CustomerID, ProductID, Quantity, OrderDate)

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 22


GUIDE:

1. Create Sample Data: Populate the Customers, Products, and Orders tables with
sample data to simulate orders.
2. Create Stored Procedure: Create a stored procedure named ProcessNewOrder that
accepts parameters for CustomerID, ProductID, and Quantity. The stored procedure
should insert a new order into the Orders table.
3. Test the Stored Procedure: Execute the stored procedure ProcessNewOrder with
sample values to test its functionality and verify that it adds new orders correctly.
4. Additional Functionality (Optional): Modify the stored procedure to include error
handling, such as checking if the specified CustomerID and ProductID exist before
inserting the order. You can also include logic to update product quantities or
calculate order totals.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 23


SAMPLE SQL CODE:

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 24


POPULATE DATA. (PLEASE ADD MORE DATA)

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 25


CREATE STORED PROCEDURE TO PROCESS NEW ORDERS

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 26


COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 27
LABORATORY EXERCISE 1
• This laboratory activity provides hands-on experience with creating a movie
database, populating it with sample data, and developing a stored procedure to
retrieve movie details.
• It covers concepts such as table creation, data insertion, stored procedure creation,
and SQL query execution within a database management context.
• Adjustments can be made to the activity based on specific learning objectives and
requirements.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 28


ACTIVITY STEP 1:
Create Sample Database:
• Open SQL Server Management Studio (SSMS) or your preferred SQL database
management tool.
• Create a new database named MovieDB using the following SQL command:

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 29


ACTIVITY STEP 2:
Create Tables:
• Create the following tables within the MovieDB database:
• Movies (MovieID INT PRIMARY KEY, Title NVARCHAR(100), Genre
NVARCHAR(50), ReleaseYear INT, Director NVARCHAR(100))
• Actors (ActorID INT PRIMARY KEY, FirstName NVARCHAR(50), LastName
NVARCHAR(50), DOB DATE, Gender NVARCHAR(10))
• MovieCast (MovieID INT, ActorID INT, PRIMARY KEY (MovieID, ActorID),
FOREIGN KEY (MovieID) REFERENCES Movies(MovieID), FOREIGN KEY (ActorID)
REFERENCES Actors(ActorID))

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 30


ACTIVITY STEP 3:
Insert Sample Data:
• Insert sample data into the Movies table to simulate movies in the database.

• Insert sample data into the Actors table to simulate actors in the database.

• Insert sample data into the MovieCast table to simulate movie casts.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 31


ACTIVITY STEP 4:
Create Stored Procedure:
Create a stored procedure named GetMovieDetails that retrieves movie details
based on the movie title.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 32


ACTIVITY STEP 5:
Execute Stored Procedure:
• Execute the GetMovieDetails stored procedure with different movie titles to retrieve
movie details.

Experiment:
• Modify the stored procedure or create additional stored procedures to retrieve
movie details based on different criteria (e.g., genre, director, release year).
Cleanup (Optional):
• Drop the MovieDB database after completing the activity to clean up the
environment.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 33


LABORATORY EXERCISE 2
Objective:
• Create a library database.
• Populate sample data into the database tables.
• Develop a stored procedure to retrieve book details.
Create Tables:
• Create the following tables within the LibraryDB database:
• Books (BookID INT PRIMARY KEY, Title NVARCHAR(100), Author
NVARCHAR(100), Genre NVARCHAR(50), PublishYear INT)
• Members (MemberID INT PRIMARY KEY, FirstName NVARCHAR(50), LastName
NVARCHAR(50), Email NVARCHAR(100))
• BookLoans (LoanID INT PRIMARY KEY, BookID INT, MemberID INT, LoanDate
DATE, ReturnDate DATE, FOREIGN KEY (BookID) REFERENCES Books(BookID),
FOREIGN KEY (MemberID) REFERENCES Members(MemberID))

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 34


LABORATORY EXERCISE 2
Insert Sample Data: (Make at least 10 records)
• Insert sample data into the Books table to simulate books available in the library.

• Insert sample data into the Members table to simulate library members.

• Insert sample data into the BookLoans table to simulate book loans.

Create Stored Procedure:


• Create a stored procedure named GetBookDetails that retrieves book details based on the
book title.
Execute Stored Procedure:
• Execute the GetBookDetails stored procedure with different book titles to retrieve book
details.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 35


THE END.

COLLEGE OF COMPUTING AND INFORMATION TECHNOLOGY 36

You might also like