9.stored Procedures & Case Study - Internet Bookshop
9.stored Procedures & Case Study - Internet Bookshop
18CS53
1
Course objectives: This course will enable students to
1. Provide a strong foundation in database concepts, technology, and
practice.
2. Practice SQL programming through a variety of database problems.
3. Demonstrate the use of concurrency and transactions in database
4. Design and build database applications for real world problems.
Course Outcome
Course Code Course Outcome
2
Textbooks:
1. Fundamentals of Database Systems, Ramez Elmasri and
Shamkant B. Navathe, 7th Edition, 2017,Pearson.
2. Database management systems, Ramakrishnan, and Gehrke,
3rd Edition, 2014, McGraw Hill
Reference Books:
1. Silberschatz Korth and Sudharshan, Database System
Concepts, 6th Edition, Mc-GrawHill, 2013.
2. Coronel, Morris, and Rob, Database Principles Fundamentals
of Design, Implementation and Management, Cengage
Learning 2012.
3
STORED PROCEDURES
4
Subtopics to be covered under Stored Procedure
• Introduction
• Creating a Simple Stored Procedure
• Calling Stored Procedures
• SQL/PSM
• Case Study
5
Introduction
6
• When SQL statements are issued from a remote application,
the records in the result of the query need to be transferred
from the database system back to the application.
• If we use a cursor to remotely access the results of an SQL
statement, the DBMS has resources such as locks and memory
tied up while the application is processing the records
retrieved through the cursor.
7
Stored Procedure
8
• Once a stored procedure is registered with the database server,
different users can re-use the
stored procedure, eliminating duplication of efforts in writing
SQL queries or application logic, and making code
maintenance easy.
9
1.Creating a Simple Stored Procedure-Without
Arguments
CREATE PROCEDURE ShowNumberOfOrders
SELECT C.cid, C.cname, COUNT(*)
FROM Customers C, Orders a
WHERE C.cid = O.cid
GROUP BY C.cid, C.cname
10
• Stored procedures can also have parameters. These parameters have
to be valid SQL types, and have one of three different modes: IN,
OUT, or INOUT.
• IN parameters are arguments to' the stored procedure.
• OUT parameters are returned from the stored procedure; it assigns
values to all OUT parameters that the user can process.
• INOUT parameters combine the properties of IN and OUT
parameters: They contain values to be passed to the stored
procedures, and the stored procedure can set their values as return
values.
• Stored procedures enforce strict type conformance:
• If a parameter is of type INTEGER, it cannot be called with an
argument of type VARCHAR.
11
Stored Procedure-With Arguments
12
• Stored procedures do not have to be written in SQL;
• they can be written in any host language.
• As an example, the stored procedure shown in Figure is a
Java function that is dynamically executed by the
database server whenever it is called by the client:
13
2.Calling Stored Procedures
14
• In Embedded SQL, the arguments to a stored procedure are
usually variables
• in the host language. For example, the stored procedure
AddInventory would
• be called as follows:
EXEC SQL BEGIN DECLARE SECTION
char isbn[lO];
long qty;
EXEC SQL END DECLARE SECTION
/ / set isbn and qty to some values
EXEC SQL CALL AddInventory(:isbn,:qty);
15
Calling Stored Procedures from JDBC
18
In SQL/PSM, we declare a stored procedure as follows:
CREATE PROCEDURE name (parameter1,... , parameterN)
local variable declarations
procedure code;
• We can declare a function similarly as follows:
CREATE FUNCTION name (parameterl, ... , parameterN)
RETURNS sqIDataType
local variable declarations
function code;
19
We start out with an example of a SQL/PSM function that
illustrates the main SQL/PSM constructs.
The function takes as input a customer identified by her cid and a
year.
The function returns the rating of the customer, which is defined
a...'3 follows:
Customers who have bought more than ten books during the
year are rated 'two';
customer who have purchased between 5 and 10 books are
rated 'one', otherwise the
customer is rated 'zero'.
20
• The following SQL/PSM code computes the rating for a given
customer and year.
CREATE PROCEDURE RateCustomer(IN custId INTEGER, IN year
INTEGER)
RETURNS INTEGER
DECLARE rating INTEGER;
DECLARE numOrders INTEGER;
SET numOrders = (SELECT COUNT(*) FROM Orders 0 WHERE
O.tid = custId);
IF (numOrders>10) THEN rating=2;
ELSEIF (numOrders>5) THEN rating=1;
ELSE rating=O;
END IF;
RETURN rating;
21
• We can declare local variables using the DECLARE statement. In
our example, we declare two local variables: 'rating', and
'numOrders'.
• PSM/SQL functions return values via the RETURN statement. In
our example, we return the value of the local variable 'rating'.
• We can assign values to variables with the SET statement. In our
example, we assigned the return value of a query to the variable
'numOrders'.
• SQL/PSM has branches and loops. Branches have the following
form:
22
IF (condition) THEN statements;
ELSEIF statements;
ELSEIF statements;
ELSE statements; END IF
Loops are of the form
• LOOP
statements:
• END LOOP
Queries can be used as part of expressions in branches; queries that return a
single ;ralue can be assigned to variables as in our example above.
'We can use the same cursor statements &s in Embedded SQL (OPEN,
FETCH,CLOSE), but we do not need the EXEC SQL constructs, and
variables do not have to be prefixed by a colon ':'.
23
CASE STUDY: THE INTERNET BOOK SHOP
24
• DBDudes finished logical database design, and now consider
the queries that they have to support.
• They expect that the application logic will be implemented in
Java, and so they consider JDBC and SQLJ as possible
candidates for interfacing the database system with application
code.
25
• Recall that DBDudes settled on the following schema:
• Books( isbn: CHAR(10), title: CHAR(8), author: CHAR(80),
• qty_in_stock: INTEGER, price: REAL, year_published:
INTEGER)
• Customers( cid: INTEGER, cname: CHAR(80), address:
CHAR(200))
• Orders(ordernum: INTEGER, isbn: CHAR(lO), cid:
INTEGER,
• cardnum: CHAR(l6), qty: INTEGER, order_date: DATE,
ship_date: DATE)
26
Now, DBDudes considers the types of queries and updates that will arise.
They
first create a list of tasks that will be performed in the application. Tasks
performed by customers include the following.
• Customers search books by author name, title, or ISBN.
• Customers register with the website. Registered customers might want to
change their contact information. DBDudes realize that they have to
augment the Customers table with additional information to capture
login and password information for each customer; we do not discuss
this aspect any further.
• Customers check out a final shopping basket to complete a sale.
• Customers add and delete books from a 'shopping basket' at the website.
• Customers check the status of existing orders and look at old orders.
27
• Administrative tasks performed by employees of B&N are
listed next.
• Employees look up customer contact information.
• Employees add new books to the inventory.
Employees fulfill orders, and need to update the shipping date of
individual books.
• Employees analyze the data to find profitable customers and
customers likely to respond to special marketing campaigns.
• Next, DBDudes consider the types of queries that will a,rise out of
these tasks. To support searching for books by name, author, title, or
ISBN, DBDudes decide to write a stored procedure as follows:
28
CREATE PROCEDURE SearchByISBN (IN book.isbn CHAR (10) )
SELECT B.title, B.author, B.qty_in_stock,B.price, B.year_published
FROM Books B
WHERE B.isbn = book_isbn
• Placing an order involves inserting one or more records into the
Orders table.
• Since DBDudes has not yet chosen the Java-based technology to
program the application logic, they assume for now that the
individual books in the order are stored at the application layer in a
Java array.
• To finalize the order, they write the following JDBC code which
inserts the elements from the array into the
• Orders table. Note that this code fragment assumes several Java
variables have been set beforehand.
29
String sql = "INSERT INTO Orders VALUES(7, 7, 7, 7, 7, 7)";
PreparedStatement pstmt = con.prepareStatement(sql);
con.setAutoCommit(false);
try {
/ / orderList is a vector of Order objects
/ / ordernum is the current order number
/ / dd is the ID of the customer, cardnum is the credit card number
for (int i=O; iiorderList.lengthO; i++)
/ / now instantiate the parameters with values
Order currentOrder = orderList[i];
pstmt.clearParameters() ;
pstmt.setInt(l, ordernum);
pstmt.setString(2, Order.getlsbnO);
30
pstmt.setInt(3, dd);
pstmt.setString(4, creditCardNum);
pstmt.setlnt(5, Order.getQtyO);
pstmt.setDate(6, null);
pstmt.executeUpdate();
}
con.commit();
catch (SqLException e){
con.rollbackO;
System.out. println (e.getMessage());
}
31
CREATE TRIGGER update_ShipDate
AFTER INSERT ON Orders 1* Event *j
FOR EACH ROW
BEGIN CALL UpdatcShipDate(new); END 1* Action *j
32
Which of the following methods are needed for loading a
database driver in JDBC?
• A. registerDriver() method
• B. Class.forName()
• C. Both A and B
• D. getConnection()
33
How can you execute a stored procedure in the database?
• A. Call method execute() on a CallableStatement object
• B. Call method executeProcedure() on a Statement object
• C. Call method execute() on a StoredProcedure object
• D. Call method run() on a ProcedureCommand object
34
Point out the correct statement.
a) Stored procedures assist in achieving consistent
implementation of logic across applications
b) A stored procedure is a group of Transact-SQL statements
compiled into a single execution plan
c) Stored procedures can also improve performance
d) All of the mentioned
35
• Which of the following is used to input the entry and give the
result in a variable in a procedure?
a) Put and get
b) Get and put
c) Out and In
d) In and out
36
Create procedure dept_count proc(in dept name varchar(20),
out d count integer)
begin
select count(*) into d count
from instructor
where instructor.dept name= dept count proc.dept name end
Which of the following is used to call the procedure given above ?
a)Declare d_count integer;
b)Declare d_count integer; call dept_count proc(’Physics’, d_count);
c)Declare d_count integer; call dept_count proc(’Physics’);
d)Declare d_count; call dept_count proc(’Physics’, d_count);
37
Questions
38
FDP CONTENT LINK
https://nptel.ac.in/courses/106/105/106105175/ (AICTE Approved FDP link)
Self Assessment Quiz link
https://forms.gle/juPiZA1N6V2omoDD7
Innovative Content Link
1. https://www.youtube.com/watch?v=CAanqvvDsTw&list=PLEbnTDJUr_I
c_9b4PcKmlae41cyxEefot&index=11
(GATE TRAINER LINK DBMS)
2. https://www.youtube.com/watch?v=5GQbACGHY_E&list=PLL_LQvNX
4xKyiExzq9GKwORoH6nvaRnOQ&index=24
(PROFESSIONAL TRAINER FOR DBMS)
3. https://www.youtube.com/watch?v=buaSuEMi4lw
4. https://www.youtube.com/watch?v=Uld8eE016Kg
39
References
40