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

Unit IV Dbms

The document outlines the syllabus for a course on Database Management Systems, focusing on PL/SQL concepts, stored procedures, and triggers. It covers topics such as complex data types, SQL extensions, and examples of functions and procedures in MySQL. Additionally, it discusses error handling, cursors, and the use of triggers to maintain data integrity in databases.

Uploaded by

gobar626
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)
1 views

Unit IV Dbms

The document outlines the syllabus for a course on Database Management Systems, focusing on PL/SQL concepts, stored procedures, and triggers. It covers topics such as complex data types, SQL extensions, and examples of functions and procedures in MySQL. Additionally, it discusses error handling, cursors, and the use of triggers to maintain data integrity in databases.

Uploaded by

gobar626
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/ 79

CET2002B Database Management

Systems

SCHOOL OF COMPUTER ENGINEERING AND TECHNOLOGY


Syllabus

UNIT IV - INTRODUCTION TO DBMS AND DATA MODELING

PL/SQL Concepts: PL/SQL Functions and Procedures, Cursors, Database


Triggers.Complex Data Types: Semi structure data: XML, Document Type
Definitions (DTDs), XML Schemas, XPATH, XSL, XSLT
Unstructured data: JSON, Data types, Application of DBMS

10/9/2023 DBMS 2
Extensions to SQL
(PL/SQL)

10/9/2023 DBMS 3
What is PL/SQL

10/9/2023 DBMS 4
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).
• Functions written in an external languages are particularly useful with specialized
data types such as images and geometric objects.
• Example: functions to check if polygons overlap, or to compare images for
similarity.
• 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.

10/9/2023 DBMS 5
Stored Function

10/9/2023 DBMS 6
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;

where param is:


[in | out | in out] <param_name> <param_type>

10/9/2023 DBMS 7
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.
• DELIMITER $$
• CREATE FUNCTION myrand() RETURNS INT
• DETERMINISTIC
• BEGIN
• RETURN round(rand()*10000, 0);
• END$$
10/9/2023 DBMS 8
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

10/9/2023 DBMS 9
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

10/9/2023 DBMS 10
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.

10/9/2023 DBMS 11
Example 2 (Cont..)

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

O Output:

10/9/2023 DBMS 12
Example 3

10/9/2023 DBMS 13
Example 3 (cont..)

10/9/2023 DBMS 14
Stored Procedures

10/9/2023 DBMS 15
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

10/9/2023 DBMS 16
Example 1 – No parameters

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

10/9/2023 DBMS 17
Example 1 (Cont..)

▪ Calling Procedure:

CALL GetAllProducts();
▪ Output:

10/9/2023 DBMS 18
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
10/9/2023 DBMS 19
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.

10/9/2023 DBMS 20
Example 2 (Cont..)

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

10/9/2023 DBMS 21
Example 2 (Cont..)

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

10/9/2023 DBMS 22
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)

10/9/2023 DBMS 23
(Cont..)
• Procedure Call:
• mysql> CALL my_proc_OUT(@M)$$
• Query OK, 1 row affected (0.03 sec)
• mysql< SELECT @M$$

• Output:
+-------+
| @M |
+-------+
| 40000 |
+-------+
1 row in set (0.00 sec)
10/9/2023 DBMS 24
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.

10/9/2023 DBMS 25
Example 4 (Cont..)

Function
Call:

10/9/2023 DBMS 26
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

10/9/2023 DBMS 27
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

10/9/2023 DBMS 28
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:


while boolean expression do
sequence of statements ;
end while repeat
sequence of statements ;
▪ until boolean expression
end repeat
10/9/2023 DBMS 29
• DELIMITER $$
• CREATE PROCEDURE `hr`.`my_proc_CASE` (INOUT no_employees INT, IN salary INT)
• BEGIN
• CASE
• WHEN (salary>10000)
• THEN (SELECT COUNT(job_id) INTO no_employees
• FROM jobs WHERE min_salary>10000);
• WHEN (salary<10000)
• THEN (SELECT COUNT(job_id) INTO no_employees
• FROM jobs WHERE min_salary<10000);
• ELSE (SELECT COUNT(job_id) INTO no_employees
• FROM jobs WHERE min_salary=10000);
• END CASE;
• END$$

10/9/2023 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;

10/9/2023 DBMS 31
Language Constructs (Cont.)

▪ Conditional statements (if-then-else)


IF expression THEN
statements;
ELSE
else-statements;
END IF;
Example:
IF creditlim > 50000 THEN
SET p_customerLevel = 'PLATINUM';
ELSEIF (creditlim <= 50000 AND creditlim >= 10000) THEN
SET p_customerLevel = 'GOLD';
ELSEIF creditlim < 10000 THEN
SET p_customerLevel = 'SILVER';
END IF;
10/9/2023 DBMS 32
Error Handling in MySQL
▪ The following handler means that if an error occurs, set the value of the has_error variable
to 1 and continue the execution.

▪ The following is another handler which means that in case an error occurs, rollback the
previous operation, issue an error message, and exit the current code block.
▪ If we declare it inside the BEGIN END block of a stored procedure, it will terminate stored
procedure immediately.

10/9/2023 DBMS 33
Error Handling in MySQL

▪ The following handler means that if there are no more rows to fetch, in case of a
cursor or SELECT INTO statement, set the value of the no_row_found variable
to 1 and continue execution.

▪ The following handler means that if a duplicate key error occurs, MySQL error
1062 is issued. It issues an error message and continues execution.

10/9/2023 DBMS 34
Example

▪ First, create a new table named article_tags.

▪ The article_tags table stores the relationships between articles and tags. Each
article may have many tags and vice versa.
▪ Next, create a stored procedure that inserts article id and tag id into the
article_tags table.

10/9/2023 DBMS 35
Example (Cont..)

10/9/2023 DBMS 36
Example (Cont..)

▪ Then, Call the procedure

▪ After that, try to insert a duplicate key to check if the handler is really invoked.

▪ We will get an error message. However, because we declared the handler as a


CONTINUE handler, the stored procedure continued the execution. As the result,
we get the tag count for the article as well.
10/9/2023 DBMS 37
Example (Cont..)

10/9/2023 DBMS 38
Cursors

11/9/2023 DBMS 39
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.

11/9/2023 DBMS 40
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:

11/9/2023 DBMS 41
Cursors

The following diagram illustrates how MySQL cursor works.

11/9/2023 DBMS 42
Example using Cursors

 Example 2 in stored procedure updates one row in deptsal table based on


input parameter.
• Suppose we want to update all the rows in deptsal simultaneously.
• First, let’s reset the totalsalary in deptsal to zero.

11/9/2023 DBMS 43
Example using Cursors

Drop the old procedure

Use cursor to iterate the rows

11/9/2023 DBMS 44
Example using Cursors

• Call procedure :

11/9/2023 DBMS 45
Another Example

• Create a procedure to give a raise to all employees

11/9/2023 DBMS 46
Another Example (Cont..)

11/9/2023 DBMS 47
Another Example (Cont..)

11/9/2023 DBMS 48
Triggers

11/9/2023 DBMS 49
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.

11/9/2023 DBMS 50
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.

11/9/2023 DBMS 51
MySQL Trigger Syntax

11/9/2023 DBMS 52
MySQL Trigger Example 1

 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.
11/9/2023 DBMS 53
Continued…

 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.

11/9/2023 DBMS 54
Example (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:

11/9/2023 DBMS 55
Example (Cont..)

 The following is the output of the query:

11/9/2023 DBMS 56
Example 2

• We want to create a trigger to update the total salary


11/9/2023
of a department when a new employee is hired
DBMS 57
Example 2 (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


11/9/2023 DBMS 58
Example 2 (Cont..)

totalsalary increases by 90K

totalsalary did not change

11/9/2023 DBMS 59
MySQL Trigger

 To list all the triggers we have created:


mysql> show triggers;

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

11/9/2023 DBMS 60
Types of Data
• Data can be broadly classified into four types:
– Structured Data:
▪ Have a predefined model, which organizes data into a form that is relatively easy to store,
process, retrieve
and manage
▪ E.g., relational data
– Unstructured Data:
▪ Opposite of structured data
▪ E.g., Flat binary files containing text, video or audio
▪ Note: data is not completely devoid of a structure (e.g., an audio file may still have an
encoding structure and some metadata associated with it)
– Dynamic Data:
▪ Data that changes relatively frequently
▪ E.g., office documents and transactional entries in a financial database
– Static Data:
▪ Opposite of dynamic data, E.g. Medical imaging data from MRI or CT scans

Database Management System 61


Why Classifying Data?
• Segmenting data into one of the following 4 quadrants can
help in designing and developing a pertaining storage
solution
Dynamic Static

StructuredUnstructured
Media Production, Media Archive,
eCAD, mCAD, Office Broadcast, Medical
Docs Imaging

Transaction Systems,
BI, Data Warehousing
ERP, CRM

• Relational databases are usually used for structured data


• File systems or NoSQL databases can be used for (static),
unstructured data (more on these later)

Database Management System 62


XML
• XML stands for eXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to store and transport data on internet
• XML was designed to be self-descriptive
• XML is a W3C Recommendation
• XML tags are not predefined. You must define your own tags. XML is
platform independent and language independent.

63
XML
• XML is case sensitive
• All start tags must have end tags
• Elements must be properly nested
• XML declaration is the first statement
• Every document must contain a root element
• Attribute values must have quotation marks
• Certain characters are reserved for parsing

Database Management System 64


Building Blocks of XML
• Elements (Tags) are the primary components of XML
documents.
<AUTHOR id = 123>
<FNAME> JAMES</FNAME>
<LNAME> RUSSEL</LNAME>
</AUTHOR>
<!- I am comment ->

▪Attributes provide additional information about Elements.


Values of the Attributes are set inside the Elements
▪Comments stats with <!- and end with ->

Database Management System 65


Example of XML
<Book>
<Title>My Life and Times</Title>
<Author>Paul McCartney</Author>
<Date>July, 1998</Date>
<ISBN>94303-12021-43892</ISBN>
<Publisher>McMillin Publishing</Publisher>
</Book>
<Book>
<Title>Illusions The Adventures of a Reluctant Messiah</Title>
<Author>Richard Bach</Author>
<Date>1977</Date>
<ISBN>0-440-34319-4</ISBN>
<Publisher>Dell Publishing Co.</Publisher>
</Book>
<Book>
<Title>The First and Last Freedom</Title>
<Author>J. Krishnamurti</Author>
<Date>1954</Date>
<ISBN>0-06-064831-7</ISBN>
<Publisher>Harper &amp; Row</Publisher>
</Book>

Database Management System 66


XML Document Schema
• Database schemas constrain what information can be stored, and the
data types of stored values
• XML documents are not required to have an associated schema
• However, schemas are very important for XML data exchange
• Otherwise, a site cannot automatically interpret data received from another
site
• Two mechanisms for specifying XML schema
• Document Type Definition (DTD)
• Widely used
• XML Schema
• Newer, increasing use
Document Type Definition (DTD)
• The type of an XML document can be specified using a DTD
• DTD constraints structure of XML data
• What elements can occur
• What attributes can/must an element have
• What subelements can/must occur inside each element, and how many
times.
• DTD does not constrain data types
• All values represented as strings in XML
• DTD syntax
• <!ELEMENT element (subelements-specification) >
• <!ATTLIST element (attributes) >
Element Specification in DTD
• Subelements can be specified as
• names of elements, or
• #PCDATA (parsed character data), i.e., character strings
• EMPTY (no subelements) or ANY (anything can be a subelement)
• Example
<! ELEMENT department (dept_name building, budget)>
<! ELEMENT dept_name (#PCDATA)>
<! ELEMENT budget (#PCDATA)>
• Subelement specification may have regular expressions
<!ELEMENT university ( ( department | course | instructor | teaches )+)>
• Notation:
• “|” - alternatives
• “+” - 1 or more occurrences
• “*” - 0 or more occurrences
University DTD <!DOCTYPE university [
<!ELEMENT university (
(department|course|instructor|teaches)+)>
<!ELEMENT department ( dept name, building, budget)>
<!ELEMENT course ( course id, title, dept name, credits)>
<!ELEMENT instructor (IID, name, dept name, salary)>
<!ELEMENT teaches (IID, course id)>
<!ELEMENT dept name( #PCDATA )>
<!ELEMENT building( #PCDATA )>
<!ELEMENT budget( #PCDATA )>
<!ELEMENT course id ( #PCDATA )>
<!ELEMENT title ( #PCDATA )>
<!ELEMENT credits( #PCDATA )>
<!ELEMENT IID( #PCDATA )>
<!ELEMENT name( #PCDATA )>
<!ELEMENT salary( #PCDATA )>
]>
University DTD with Attributes
• University DTD with ID and IDREF attribute types.
<!DOCTYPE university-3 [
<!ELEMENT university ( (department|course|instructor)+)>
<!ELEMENT department ( building, budget )>
<!ATTLIST department
dept_name ID #REQUIRED >
<!ELEMENT course (title, credits )>
<!ATTLIST course
course_id ID #REQUIRED
dept_name IDREF #REQUIRED
instructors IDREFS #IMPLIED >
<!ELEMENT instructor ( name, salary )>
<!ATTLIST instructor
IID ID #REQUIRED
dept_name IDREF #REQUIRED >
· · · declarations for title, credits, building,
budget, name and salary · · ·
]>
Limitations of DTDs
• No typing of text elements and attributes
• All values are strings, no integers, reals, etc.
• Difficult to specify unordered sets of subelements
• Order is usually irrelevant in databases (unlike in the document-layout
environment from which XML evolved)
• (A | B)* allows specification of an unordered set, but
• Cannot ensure that each of A and B occurs only once
• IDs and IDREFs are untyped
• The instructors attribute of an course may contain a reference to another
course, which is meaningless
• instructors attribute should ideally be constrained to refer to instructor elements
XML Schema
• XML Schema is a more sophisticated schema language which addresses the
drawbacks of DTDs. Supports
• Typing of values
• E.g. integer, string, etc
• Also, constraints on min/max values
• User-defined, comlex types
• Many more features, including
• uniqueness and foreign key constraints, inheritance
• XML Schema is itself specified in XML syntax, unlike DTDs
• More-standard representation, but verbose
• XML Scheme is integrated with namespaces
• BUT: XML Schema is significantly more complicated than DTDs.
XML Schema Version of Univ. DTD
<xs:schema xmlns:xs=“http://www.w3.org/2001/XMLSchema”>
<xs:element name=“university” type=“universityType” />
<xs:element name=“department”>
<xs:complexType>
<xs:sequence>
<xs:element name=“dept name” type=“xs:string”/>
<xs:element name=“building” type=“xs:string”/>
<xs:element name=“budget” type=“xs:decimal”/>
</xs:sequence>
</xs:complexType>
</xs:element>
….
<xs:element name=“instructor”>
<xs:complexType>
<xs:sequence>
<xs:element name=“IID” type=“xs:string”/>
<xs:element name=“name” type=“xs:string”/>
<xs:element name=“dept name” type=“xs:string”/>
<xs:element name=“salary” type=“xs:decimal”/>
</xs:sequence>
</xs:complexType>
</xs:element>
… Contd.
XML Schema
….
Version of Univ. DTD (Cont.)
<xs:complexType name=“UniversityType”>
<xs:sequence>
<xs:element ref=“department” minOccurs=“0” maxOccurs=“unbounded”/>
<xs:element ref=“course” minOccurs=“0” maxOccurs=“unbounded”/>
<xs:element ref=“instructor” minOccurs=“0” maxOccurs=“unbounded”/>
<xs:element ref=“teaches” minOccurs=“0” maxOccurs=“unbounded”/>
</xs:sequence>
</xs:complexType>
</xs:schema>

● Choice of “xs:” was ours -- any other namespace prefix could be


chosen
● Element “university” has type “universityType”, which is defined
separately
● xs:complexType is used later to create the named complex type
“UniversityType”
Querying and Transforming XML Data
• Translation of information from one XML schema to another
• Querying on XML data
• Above two are closely related, and handled by the same tools
• Standard XML querying/translation languages
• XPath
• Simple language consisting of path expressions
• XSLT
• Simple language designed for translation from XML to XML and XML to HTML
• XQuery
• An XML query language with a rich set of features
JSON
• JSON stands for “JavaScript Object Notation”, a
simple data interchange format.
• JSON is often used when data is sent from a server to
a web page
• JSON is "self-describing" and easy to understand.
• a JavaScript program can easily convert JSON data
into native JavaScript objects.

Database Management System 77


DBMS Applications
References

1. Silberschatz−Korth−Sudarshan's Database System Concepts, Seventh


Edition.
2. MySQL Tutorial
http://www.mysqltutorial.org/

DBMS 79
11/9/2023

You might also like