0% found this document useful (0 votes)
3 views

Unit_IV_Part_I

The document outlines the course objectives and outcomes for CS312 Database Management Systems, focusing on logical database design, programming languages, transaction processing, and database architectures. It covers PL/SQL, including its advantages, functions, procedures, and the use of cursors and triggers in database management. Examples illustrate the application of these concepts in real-world scenarios, such as defining functions and creating triggers.

Uploaded by

heramb.churi
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)
3 views

Unit_IV_Part_I

The document outlines the course objectives and outcomes for CS312 Database Management Systems, focusing on logical database design, programming languages, transaction processing, and database architectures. It covers PL/SQL, including its advantages, functions, procedures, and the use of cursors and triggers in database management. Examples illustrate the application of these concepts in real-world scenarios, such as defining functions and creating triggers.

Uploaded by

heramb.churi
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/ 100

CS312

Database Management Systems

School of Computer Engineering and Technology


CS312 Database Management Systems
Course Objectives:
1) Understand and successfully apply logical database design principles, including E-R
diagrams and database normalization.
2) Learn Database Programming languages and apply in DBMS application
3) Understand transaction processing and concurrency control in DBMS
4) Learn database architectures, DBMS advancements and its usage in advance
application

Course Outcomes:
5) Design ER-models to represent simple database application scenarios and Improve the
database design by normalization.
6) Design Database Relational Model and apply SQL , PLSQL concepts for database
programming
7) Describe Transaction Processing and Concurrency Control techniques for databases
8) Identify appropriate database architecture for the real world database application
Extensions to SQL
(PL/SQL)

8/13/2020 DBMS 3
What is PL/SQL

8/13/2020 DBMS 4
PL/SQL Execution
Advantages
• PL/SQL is a completely portable, high-
performance transaction-processing
language.
• PL/SQL provides a built-in, interpreted
and OS independent programming
environment.
• It supports structured programming
through functions and procedures.
• Direct call can also be made from external
programming language calls to database.

8/13/2020 DBMS 5
PL/SQL Functions and Procedures
 SQL:1999 supports functions and procedures
– Functions/procedures can be written in SQL itself, or in an external programming language
(e.g., C, Java).
– Some database systems support table-valued functions, which can return a relation as a
result.
 SQL:1999 also supports a rich set of imperative constructs, including
– Loops, if-then-else, assignment
 Many databases have proprietary procedural extensions to SQL that differ from SQL:1999.
 Procedures and functions are stored in mysql.routines
and mysql.parameters tables, which are part of the data dictionary.

8/13/2020 6
DBMS
Stored Function

8/13/2020 DBMS 7
PL/SQL Functions

 Functions are declared using the following syntax:


Create function <function-name> (param_1, …, param_k)
returns <return_type>
[not] deterministic allow optimization if same output
for the same input (use RAND not deterministic )
Begin
-- execution code
end;

For a FUNCTION, parameters are always regarded as IN parameters.


For a Procedure , parameter as IN, OUT, or INOUT is valid.

8/13/2020 DBMS 8
Deterministic and Non- deterministic Functions
• A deterministic function always returns the same result for the same input
parameters whereas a non-deterministic function returns different results for the
same input parameters.
• If you don’t use DETERMINISTIC or NOT DETERMINISTIC, MySQL uses the
NOT DETERMINISTIC option by default.
• rand() is nondeterministic function. That means we do not know what it will return
ahead of time.
• Some deterministic functions
• ISNULL, ISNUMERIC, DATEDIFF, POWER, CEILING, FLOOR, DATEADD,
DAY, MONTH, YEAR, SQUARE, SQRT etc.
• Some non deterministic functions
• RAND(), RANK(), SYSDATE()

8/13/2020 DBMS 9
PL/SQL Functions – Example 1

 Define a function that, given the name of a department, returns the count of the
number of instructors in that department.

create function dept_count (dept_name varchar(20))


returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
8/13/2020 DBMS 10
Example 1 (Cont)..

 The function dept_count can be used to find the department names and budget of
all departments with more than 12 instructors.

select dept_name, budget


from department
where dept_count (dept_name ) > 12

8/13/2020 DBMS 11
Example 2

 A function that returns the level of a customer based on credit limit. We use the IF
statement to determine the credit limit.

8/13/2020 DBMS 12
Example 2 (Cont..)

• Calling function:
• we can call the CustomerLevel() in a SELECT statement as follows:

O Output:

8/13/2020 DBMS 13
Example 3

8/13/2020 DBMS 14
Example 3 (cont..)

8/13/2020 DBMS 15
Stored Procedures

8/13/2020 DBMS 16
Stored Procedures in MySQL
 A stored procedure contains a sequence of SQL commands stored in the database catalog so
that it can be invoked later by a program
 Stored procedures are declared using the following syntax:
Create Procedure <proc-name>
(param_spec1, param_spec2,param_specn )
begin
-- execution code
end;
where each param_spec is of the form:
[in | out | inout] <param_name> <param_type>
– in mode: allows you to pass values into the procedure,
– out mode: allows you to pass value back from procedure to the calling program, initial
value in the procedure is taken as null .
– Inout mode : allows you to pass value DBMS
8/13/2020 back from procedure to the calling program, initial
17
Example 1 – No parameters

 The GetAllProducts() stored procedure selects all products from the products
table.

8/13/2020 DBMS 18
Example 1 (Cont..)

 Calling Procedure:

CALL GetAllProducts();
 Output:

8/13/2020 DBMS 19
Example 2 ( with IN parameter)

• Suppose we want to keep track of the total salaries of employees working for each
department

We need to write a procedure


to update the salaries in
the deptsal table
8/13/2020 DBMS 20
Example 2 (Cont..)

1. Define a procedure called updateSalary which takes as input a department number.


2. The body of the procedure is an SQL command to update the totalsalary column of
the deptsal table.

8/13/2020 DBMS 21
Example 2 (Cont..)

Step 3: Call the procedure to update the totalsalary for each department

8/13/2020 DBMS 22
Example 2 (Cont..)

Step 4: Show the updated total salary in the deptsal table

8/13/2020 DBMS 23
Example 3 (with OUT Parameter)

 The following example shows a simple stored procedure that uses an OUT
parameter.
 Within the procedure MySQL MAX() function retrieves maximum salary from
MAX_SALARY of jobs table.

mysql> CREATE PROCEDURE my_proc_OUT (OUT highest_salary INT)


-> BEGIN
-> SELECT MAX(MAX_SALARY) INTO highest_salary FROM JOBS;
-> END$$
Query OK, 0 rows affected (0.00 sec)

8/13/2020 DBMS 24
(Cont..)
• Procedure Call:
mysql> CALL my_proc_OUT(@M)$$
Query OK, 1 row affected (0.03 sec)
• To see the result type the following command
mysql< SELECT @M$$

• Output:
+-------+
| @M |
+-------+
| 40000 |
+-------+
1 row in set (0.00 sec)
8/13/2020 DBMS 25
Example 4 (with INOUT Parameter)

 The following example shows a simple stored procedure that uses an INOUT
parameter.
 ‘count’ is the INOUT parameter, which can store and return values and
‘increment’ is the IN parameter, which accepts the values from user.

8/13/2020 DBMS 26
Example 4 (Cont..)

Function
Call:

8/13/2020 DBMS 27
Stored Procedures (Cont..)

 Use show procedure status to display the list of stored procedures you have
created

 Use drop procedure to remove a stored procedure

8/13/2020 DBMS 28
Language Constructs for Procedures &
Functions
 SQL supports constructs that gives it almost all the power of a general-purpose
programming language.
o Warning: most database systems implement their own variant of the
standard syntax below.
 Compound statement: begin … end,
o May contain multiple SQL statements between begin and end.
o Local variables can be declared within a compound statements

8/13/2020 DBMS 29
Language Constructs
 CASE Statement
CASE case_expression
WHEN when_expression_1 THEN commands
WHEN when_expression_2 THEN commands
...
ELSE commands
END CASE;

 While and repeat statements:


repeat
while boolean expression do
sequence of statements ;
sequence of statements ;
end while until boolean expression
end repeat


8/13/2020 DBMS 30
Language Constructs (Cont.)

 Loop, Leave and Iterate statements…


– Permits iteration over all results of a query.
loop_label: LOOP
IF x > 10 THEN
LEAVE loop_label;
END IF;
SET x = x + 1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
END IF;
END LOOP;
8/13/2020 DBMS 31
Cursors

8/30/2020 DBMS 2
Cursors

 To handle a result set inside a stored procedure, we use a cursor.


 A cursor allows us to iterate a set of rows returned by a query and process
each row accordingly.
 The set of rows the cursor holds is referred to as the active set.

1. We can declare a cursor by using the DECLARE statement:

• The cursor declaration must be after any variable declaration.


• A cursor must always be associated with a SELECT statement.

8/30/2020 DBMS 3
Cursors

2. Next, open the cursor by using the OPEN statement.

3. Then, use the FETCH statement to retrieve the next row pointed by the cursor and
move the cursor to the next row in the result set.

4. Finally, call the CLOSE statement to deactivate the cursor and release the memory
associated with it as follows:

8/30/2020 DBMS 4
Cursors

The following diagram illustrates how MySQL cursor works.

8/30/2020 DBMS 5
Example 1 - Cursors
1) Retrieve employees one by one and print out a list of those employees currently
working in the DEPARTMENT_ID = 80

8/30/2020 DBMS 6
Example 2
2) Use a cursor to retrieve employee numbers and names from employee table and
populate a database table, TEMP_LIST, with this information.

8/30/2020 DBMS 7
Example 3
3. Create a PL/SQL block that determines the top employees with respect to salaries.
Accept a number n from the user where n represents the number of top n earners
from the EMPLOYEES table. For example, to view the top five earners, enter 5.
Test a variety of special cases, such as n = 0 or where n is greater than the number
of employees in the EMPLOYEES table. The output shown represents the five
highest salaries in the EMPLOYEES table.

8/30/2020 DBMS 8
Cont..

8/30/2020 DBMS 9
Example 4

4. Update all the rows in deptsal simultaneously.


First, let’s reset the totalsalary in deptsal to zero.

8/30/2020 DBMS 10
Cont..

Drop the old procedure

Use cursor to iterate the rows

8/30/2020 DBMS 11
Cont..

• Call procedure :

8/30/2020 DBMS 12
Example 5
5. Create a procedure to give a raise to all employees

8/30/2020 DBMS 13
Cont..

8/30/2020 DBMS 14
Cont..

8/30/2020 DBMS 15
Triggers

8/30/2020 DBMS 16
Triggers

 A trigger is a statement that is executed automatically by the system as a side


effect of a modification to the database i.e. when changes are made to the table.
 To monitor a database and take a corrective action when a condition occurs
Examples:
• Charge $10 overdraft fee if the balance of an account after a withdrawal
transaction is less than $500
• Limit the salary increase of an employee to no more than 5% raise
 SQL triggers provide an alternative way to check the integrity of data.

8/30/2020 DBMS 17
Triggering Events and Actions in SQL

 A trigger can be defined to be invoked either before or after the data is changed
by INSERT, UPDATE or DELETE .
 MySQL allows you to define maximum six triggers for each table.
 BEFORE INSERT – activated before data is inserted into the table.
 AFTER INSERT- activated after data is inserted into the table.
 BEFORE UPDATE – activated before data in the table is updated.
 AFTER UPDATE - activated after data in the table is updated.
 BEFORE DELETE – activated before data is removed from the table.
 AFTER DELETE – activated after data is removed from the table.

8/30/2020 DBMS 18
MySQL Trigger Syntax

8/30/2020 DBMS 19
Cont..

 In a trigger defined for INSERT, you can use NEW keyword only.
You cannot use the OLD keyword.
 However, in the trigger defined for DELETE, there is no new row so
you can use the OLD keyword only.
 In the UPDATE trigger, OLD refers to the row before it is updated
and NEW refers to the row after it is updated.

8/30/2020 DBMS 20
Example 1 - Trigger
1. Create a trigger to simulate Recycle Bin for employee table. If any row gets deleted from
Emp, same row must get stored in Emp_Bin
Emp(Eno,Ename,Salary)
Emp_Bin(Eno,Ename,Salary)

8/30/2020 DBMS 21
Example 2
2. Create a BEFORE UPDATE trigger that is invoked before a change is made to the
employees table.
 we used the OLD keyword to access employeeNumber and lastname column of the row
affected by the trigger.

8/30/2020 DBMS 22
Cont..

 Update the employees table to check whether the trigger is invoked.

 Finally, to check if the trigger was invoked by the UPDATE statement, we


can query the employees_audit table using the following query:

8/30/2020 DBMS 23
Cont..

 The following is the output of the query:

8/30/2020 DBMS 24
Example 3
3. We want to create a trigger to update the total salary of a department when a
new employee is hired.

8/30/2020 DBMS 25
Cont..
Create a trigger to update the total salary of a department when a new employee is hired.

• The keyword “new” refers to the new row inserted


8/30/2020 DBMS 26
Cont..

totalsalary increases by 90K

totalsalary did not change

8/30/2020 DBMS 27
Trigger
 To list all the triggers we have created:
mysql> show triggers;

 To drop a trigger
mysql> drop trigger <trigger name>

8/30/2020 DBMS 28
XML (Extensible Markup Language)
XML is a markup language similar to HTML, but without predefined tags to use.
Instead, you define your own tags designed specifically for your needs.
This is a powerful way to store data in a format that can be stored, searched,
and shared.
Structure of XML data
XML Element
Attributes
Attributes vs. Subelements
Namespaces
Document Type Definition (DTD)
Element Specification in DTD
University DTD
Attribute Specification in DTD
Attribute Specification in DTD : examples
IDs and IDREFs
University DTD with Attributes
XML data with ID and IDREF attributes
XML Schema
XML Schema Version of Univ. DTD
XML Schema Version of Univ. DTD (Cont.)
More features of XML Schema
Querying and Transforming XML Data
Tree Model of XML Data
Tree Representation
XPath
XPath (Cont.)
Functions in XPath
More XPath Features
Extensible Stylesheet Language (XSL)

XSL is a language for expressing stylesheets



support for browsing, printing, and aural rendering

formatting highly structured documents (XML)

performing complex publishing tasks: tables of contents, indexes,
reports,...

addressing accessibility and internationalization issues

written in XML
XSL Components

XSL is constituted of three main components:



XSLT: a transformation language

XPath: an expression language for addressing parts of XML
documents

FO: a vocabulary of formatting objects with their associated
formatting properties

XSL uses XSLT which uses XPath


XSLT - Basic Principle

Patterns and Templates



A style sheets describes transformation rules

A transformation rule: a pattern + a template

Pattern: a configuration in the source tree

Template: a structure to be instantiated in the result tree

When a pattern is matched in the source tree, the
corresponding pattern is generated in the result tree
XPath: XML Path Language

An elementary XPath expression contains



an axis, which specifies the tree relationship: child, descendants,
ancestors, siblings, attributes,...

a node test, which specifies the node type

predicates, to further refine the set of nodes selected

Example: all para children that have a type attribute with value
warning

child::para[attribute::type="warning"]
XSL Usage


Format XML documents by generating FOs

Generate HTML or XHTML pages from XML data/documents

Transform XML documents into other XML documents

Generate some textual representation of an XML document

...and more

XSL may be used server-side or client-side,


but is not intended to send FOs over the wire
JSON
Thank You!

DATABASE MANAGEMENT SYSTEM LABORATORY 44


7/17/2020

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy