Slides by: Ms. Shree Jaswal

Similar documents
Unit 2: SQL AND PL/SQL

Database System Concepts

Programming the Database

PL/SQL Block structure

ORACLE: PL/SQL Programming

Domain Constraints Referential Integrity Assertions Triggers. Authorization Authorization in SQL

Introduction to Computer Science and Business

5. Single-row function

Database System Concepts"

COSC344 Database Theory and Applications. Lecture 11 Triggers

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

Database System Concepts, 5th Ed.! Silberschatz, Korth and Sudarshan See for conditions on re-use "

Procedural Language Structured Query Language (PL/SQL)

PL/SQL. Exception. When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number

RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND ANSWERS

PL/SQL is a combination of SQL along with the procedural features of programming languages.

UNIT-IV (Relational Database Language, PL/SQL)

Lesson B Objectives IF/THEN. Chapter 4B: More Advanced PL/SQL Programming

INDEX. 1 Introduction. 2 Types of Cursors 2.1 Explicit cursor 2.2 Attributes 2.3 Implicit cursor 2.4 Attributes. 3 Parameterized cursor

Principles of Data Management

Contents I Introduction 1 Introduction to PL/SQL iii

Oracle Database: Introduction to SQL/PLSQL Accelerated

Introduction to SQL/PLSQL Accelerated Ed 2

PLSQL Interview Questions :

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Lecture 08. Spring 2018 Borough of Manhattan Community College

SQL Interview Questions

Section I : Section II : Question 1. Question 2. Question 3.

ORACLE DATABASE 12C INTRODUCTION

Course 492 Supplementary Materials. Mutating Tables

DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E)

PL / SQL Basics. Chapter 3

UNIT II PL / SQL AND TRIGGERS

Chapter 4: Intermediate SQL

2. Programming written ( main theme is to test our data structure knowledge, proficiency

ORACLE Job Placement Paper. Paper Type : General - other

Textbook: Chapter 4. Chapter 5: Intermediate SQL. CS425 Fall 2016 Boris Glavic. Chapter 5: Intermediate SQL. View Definition.

Trigger is a stored procedure which is called implicitly by oracle engine whenever a insert, update or delete statement is fired.

Oracle Class VI. Exception Block Cursors For Loops

First lecture of this chapter is in slides (PPT file)

Table of Contents. Oracle SQL PL/SQL Training Courses

Meet MariaDB Vicențiu Ciorbaru Software MariaDB Foundation * * 2017 MariaDB Foundation

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

5 Integrity Constraints and Triggers

CS425 Fall 2017 Boris Glavic Chapter 5: Intermediate SQL

Question Bank PL/SQL Fundamentals-I

Chapter 4: Intermediate SQL

Sisteme Informatice şi Standarde Deschise (SISD) Curs 7 Standarde pentru programarea bazelor de date (1)

Lab # 4. Data Definition Language (DDL)

Chapter 6: Integrity and Security.! Domain Constraints! Referential Integrity! Assertions! Triggers! Security! Authorization! Authorization in SQL

RNDr. Michal Kopecký, Ph.D. Department of Software Engineering, Faculty of Mathematics and Physics, Charles University in Prague

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

DATABASE DESIGN - 1DL400

Sample Question Paper

Chapter 9: Object-Relational Databases

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

Object-Relational Data Models. Chapter 9: Object-Relational Databases. Example of a Nested Relation. Nested Relations

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C

Chapter 5: Advanced SQL" Chapter 5: Advanced SQL"

1 Prepared By Heena Patel (Asst. Prof)

Oracle SQL & PL SQL Course

Topics Fundamentals of PL/SQL, Integration with PROIV SuperLayer and use within Glovia

M.SC(IT) I YEAR( ) CORE: ADVANCED DBMS-163B Semester : I Multiple Choice Questions

Oracle PLSQL Training Syllabus

When a database trigger routine does not have to take place before the triggering event, which timing should you assign to the trigger?

Oracle PL/SQL - 12c & 11g [Basic PL/SQL & Advanced PL/SQL]

Oracle Database 12c: Program with PL/SQL Duration: 5 Days Method: Instructor-Led

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

Database Management Systems Triggers

M.C.A. (CBCS) Sem.-III Examination November-2013 CCA-3004 : Database Concepts and Tools. Faculty Code: 003 Subject Code:

Question No : 1 Which statement is true about triggers on data definition language (DDL) statements?

Oracle Database: Program with PL/SQL

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE.

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Slides by: Ms. Shree Jaswal

Introduction p. 1 The Logical and Physical View of Tables p. 1 Database Types p. 4 NULLs p. 6 DDL and DML Statements p. 7 Column and Table Constraint

Control Structures. Control Structures 3-1

Part 18: Application Programming II (Stored Procedures,Triggers)

CSE 565 Computer Security Fall 2018

Oracle PLSQL. Course Summary. Duration. Objectives

Oracle Database 11g: SQL and PL/SQL Fundamentals

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

Creating and Managing Tables Schedule: Timing Topic

Creating SQL Tables and using Data Types

ORACLE TRAINING. ORACLE Training Course syllabus ORACLE SQL ORACLE PLSQL. Oracle SQL Training Syllabus

Course Logistics & Chapter 1 Introduction

Data Definition Guide InterBase 2009

Oracle. SQL(Structured Query Language) Introduction of DBMS. Build In Function. Introduction of RDBMS. Grouping the Result of a Query

Databases 1. SQL/PSM and Oracle PL/SQL

Oracle Database: Program with PL/SQL

Oracle Database: Program with PL/SQL Ed 2

Chapter 1 SQL and Data

Oracle Database 12c R2: Program with PL/SQL Ed 2 Duration: 5 Days

CSC 261/461 Database Systems Lecture 6. Fall 2017

Conditionally control code flow (loops, control structures). Create stored procedures and functions.

Oracle Database 11g: Program with PL/SQL Release 2

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Oracle Database: SQL and PL/SQL Fundamentals NEW

Question: Which statement would you use to invoke a stored procedure in isql*plus?

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

Transcription:

Slides by: Ms. Shree Jaswal

A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. To design a trigger mechanism, we must: Specify the conditions under which the trigger is to be executed. Specify the actions to be taken when the trigger executes. Triggers introduced to SQL standard in SQL:1999, but supported even earlier using non-standard syntax by most databases. Syntax illustrated here may not work exactly on your database system; check the system manuals Module 4 Slides by: Shree Jaswal 2

Triggering event can be insert, delete or update Triggers on update can be restricted to specific attributes For example, after update of takes on grade Values of attributes before and after an update can be referenced referencing old row as : for deletes and updates referencing new row as : for inserts and updates Module 4 Slides by: Shree Jaswal 3

Triggers can be activated before an event, which can serve as extra constraints. For example, convert blank grades to null. create trigger setnull_trigger before update of takes referencing new row as nrow for each row when (nrow.grade = ) begin atomic set nrow.grade = null; end; Module 4 Slides by: Shree Jaswal 4

Instead of executing a separate action for each affected row, a single action can be executed for all rows affected by a transaction Use for each statement instead of for each row Use referencing old table or referencing new table to refer to temporary tables (called transition tables) containing the affected rows Can be more efficient when dealing with SQL statements that update a large number of rows Module 4 Slides by: Shree Jaswal 5

Triggers were used earlier for tasks such as Maintaining summary data (e.g., total salary of each department) Replicating databases by recording changes to special relations (called change or delta relations) and having a separate process that applies the changes over to a replica There are better ways of doing these now: Databases today provide built in materialized view facilities to maintain summary data Databases provide built-in support for replication Module 4 Slides by: Shree Jaswal 6

Encapsulation facilities can be used instead of triggers in many cases Define methods to update fields Carry out actions as part of the update methods instead of through a trigger Risk of unintended execution of triggers, for example, when Loading data from a backup copy Replicating updates at a remote site Trigger execution can be disabled before such actions. Other risks with triggers: Error leading to failure of critical transactions that set off the trigger Cascading execution Module 4 Slides by: Shree Jaswal 7

Procedural Language SQL Extends SQL by adding control structures found in other procedural language Higher productivity Better performance Portability Module 4 Slides by: Shree Jaswal 9

Host program or Oracle tool ORACLE SERVER PL/SQL ENGINE Anonymous PL/SQL Block Anonymous PL/SQL Block procedur al Procedural Statement Executor S Q L SQL Statement Executor Module 4 Slides by: Shree Jaswal 10

DECLARE DECLARATIONS BEGIN EXECUTABLE STATEMENTS EXCEPTION HANDLERS END; Module 4 Slides by: Shree Jaswal 11

Lower and upper case letters Numerals from 0 to 9 All special symbols and characters Tab,space and carriage return Module 4 Slides by: Shree Jaswal 12

Identifiers Literals Comments Delimiters Example Total:=salary *0.90; Total and salary are identifiers And ; simple symbols -- comment Module 4 Slides by: Shree Jaswal 13

Simple symbols : + - * / = < > % Statement terminator ; : host variable indicator /* */ multiline comment << >> label delimiter Module 4 Slides by: Shree Jaswal 14

Allows us to refer to data types and objects from the database %type: used when declaring variables that refer to the database columns Vcode vendor_master.vencode%type; Adv: we need not know the exact datatype and if the datatype changes it will be automatically reflected in PL/SQL %rowtype: provides record type that represents a row in a table Vend-inf vendor_master%rowtype; Module 4 Slides by: Shree Jaswal 15

Comparison of variables and constants in SQL and PL/SQL are called Boolean expression Numeric Character date Module 4 Slides by: Shree Jaswal 16

Conditional control (if, else loops) Iterative control (simple loops, for, while) Sequential control (GOTO) The label, which is enclosed within double angle brackets must precede an executable SQL statements or a PL/SQL block Declare --- Begin ----- Goto <<AA>>; --- <<AA>> ----- End; Module 4 Slides by: Shree Jaswal 17

Predefined exceptions User-defined exceptions Module 4 Slides by: Shree Jaswal 18

No_data_found : when select statement returns no rows Too_many_rows: raised when the select into statement returns more than one row Login_denied: when username and password is wrong Declare Module 4 Slides by: Shree Jaswal Begin Seq of statements; Exception When<exception_name> then Seq of statemnt; When others then Sequence of statemnts; End; 19

User defined exception should be declared and raised explicitly by a raise statement. <exception-name> exception; raise <exception-name>; Module 4 Slides by: Shree Jaswal 20

When a single value or row has to be fetched from a database then SELECT INTO can be used SELECT column1, column2, column3,... INTO newtable [IN externaldb] FROM oldtable WHERE condition; Declare X number; Begin Select salary into x from emp where empno=7782; If x>5000 then Dbms_output.put_line( tax payers ); Else Dbms_output.put_line( non tax payers ); End if; Exception When no_data_found then Dbms_output.put_line( not a valid empno ); End; Module 4 Slides by: Shree Jaswal 21

Select..into clause should use proper number of variables of proper datatype after the into clause Select..into clause should return only one row. If no row is selected, then an exception no_data_found is raised. If more than one row is selected then an exception too_many_rows is raised Module 4 Slides by: Shree Jaswal 22

Cursors are used when you want to manipulate data of many rows. When select..into or any DML is issued, oracle internally opens the cursor. This is called implicit cursor When queries return more than one row then the cursor has to be defined explicitly. This is called explicit cursor Module 4 Slides by: Shree Jaswal 23

Static cursor Explicit cursor Implicit cursor Dynamic cursor REF cursor Strong cursor Weak cursor Module 4 Slides by: Shree Jaswal 24

Cursor declaration Declare Cursor<cursorname> is <select statement> Open cursor Open cursorname Fetching rows from cursor Fetch cursor into cursorvariable Closing a cursor Close cursorvariable Module 4 Slides by: Shree Jaswal 25

Declare Cursor c1 is.. Begin Open c1; Fetch.. Close c1; Exception When others then. Close c1; End; Module 4 Slides by: Shree Jaswal 26

Declare Cursor c1 is select ename from emp where deptno=10; Z c1%type; Begin Open c1; Fetch c1 into z; While(c1%found) loop Dbms_output.put_line(z.ename); End loop; Close c1; End; Module 4 Slides by: Shree Jaswal 27

Cursorname%attribute C1%found C1%notfound C1%isopen C1%rowcount Module 4 Slides by: Shree Jaswal 28

Declare Cursor a is select * from order_detail where orderno= o001 ; Myorder order_detail%rowtype; Begin Open a; Loop Fetch a into myorder; Exit when a%notfound; Dbms_output.put_line( fetched a%rowcount from table ); End loop; End; / Module 4 Slides by: Shree Jaswal 29

For <record name> in <cursor_name> loop Sequence_of_statements; End loop; Declare Cursor for_cur is select orderno from order_master where vencode= v002 ; Cust_rec for_cur%rowtype; Begin For cust_rec in for_cur loop Delete from order_detail where orderno=cust_rec.orderno; End loop; Dbms_output.put_line( details has been deleted ); End; Module 4 Slides by: Shree Jaswal 30

31 Module 4 Slides by: Shree Jaswal

The information in your database is important. Therefore, you need a way to protect it against unauthorized access, malicious destruction or alteration, and accidental introduction of data inconsistency. Module 4 Slides by: Shree Jaswal 32

Database Security refers to protection from malicious access. Absolute protection is impossible Therefore, make the cost to the perpetrator so high it will deter most attempts Module 4 Slides by: Shree Jaswal 33

Some forms of malicious access: Unauthorized reading (theft) of data Unauthorized modification of data Unauthorized destruction of data To protect a database, we must take security measures at several levels. Module 4 Slides by: Shree Jaswal 34

Database System: Since some users may modify data while some may only query, it is the job of the system to enforce authorization rules. Operating System: No matter how secure the database system is, the operating system may serve as another means of unauthorized access. Network: Since most databases allow remote access, hardware and software security is crucial. Physical: Sites with computer systems must be physically secured against entry by intruders or terrorists. Human: Users must be authorized carefully to reduce the chance of a user giving access to an intruder. Module 4 Slides by: Shree Jaswal 35

For security purposes, we may assign a user several forms of authorization on parts of the databases which allow: Read: read tuples. Insert: insert new tuple, not modify existing tuples. Update: modification, not deletion, of tuples. Delete: deletion of tuples. We may assign the user all, none, or a combination of these. Module 4 Slides by: Shree Jaswal 36

In addition to the previously mentioned, we may also assign a user rights to modify the database schema: Index: allows creation and modification of indices. Resource: allows creation of new relations. Alteration: addition or deletion of attributes in a tuple. Drop: allows the deletion of relations. Module 4 Slides by: Shree Jaswal 37

The SQL language offers a fairly powerful mechanism for defining authorizations by using privileges. Module 4 Slides by: Shree Jaswal 38

SQL standard includes the privileges: Delete Insert Select Update References: permits declaration of foreign keys. SQL includes commands to grant and revoke privileges. Module 4 Slides by: Shree Jaswal 39

EX1: grant <privilege list> on <relation or view name> to <user> EX2: grant update (amount) on loan to U1, U3, U4 Module 4 Slides by: Shree Jaswal 40

By default, a user granted privileges is not allowed to grant those privileges to other users. To allow this, we append the term with grant option clause to the appropriate grant command. EX1: grant select on branch to U1 with grant option Module 4 Slides by: Shree Jaswal 41

To revoke a privilege we use the revoke clause, which is used very much like grant. EX1: revoke <privilege list> on <relation or view name> from <user list> Module 4 Slides by: Shree Jaswal 42

It is essential to ensure that the data in a database is accurate. It is also important to protect the database from domain and referential integrity violations. If the data is inaccurate or lacks integrity then the database loses effectiveness! Module 4 Slides by: Shree Jaswal 43

We must also ensure that unauthorized users are prevented from accessing or modifying our database. To do this, we implement authorization rules for users called privileges. Module 4 Slides by: Shree Jaswal 44

45 Module 4 Slides by: Shree Jaswal

API (application-program interface) for a program to interact with a database server Application makes calls to Connect with the database server Send SQL commands to the database server Fetch tuples of result one-by-one into program variables Module 4 Slides by: Shree Jaswal 46

Various tools: JDBC (Java Database Connectivity) works with Java ODBC (Open Database Connectivity) works with C, C++, C#, and Visual Basic. Other API s such as ADO.NET sit on top of ODBC Embedded SQL Module 4 Slides by: Shree Jaswal 47

JDBC is a Java API for communicating with database systems supporting SQL. JDBC supports a variety of features for querying and updating data, and for retrieving query results. JDBC also supports metadata retrieval, such as querying about relations present in the database and the names and types of relation attributes. Model for communicating with the database: Open a connection Create a statement object Execute queries using the Statement object to send queries and fetch results Exception mechanism to handle errors Module 4 Slides by: Shree Jaswal 48

49 Module 4 Slides by: Shree Jaswal

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. Module 4 Slides by: Shree Jaswal 50

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 The function dept_count can be used to find the department names and budget of all departments with more that 12 instructors. select dept_name, budget from department where dept_count (dept_name ) > 12 Module 4 Slides by: Shree Jaswal 51

Compound statement: begin end May contain multiple SQL statements between begin and end. returns -- indicates the variable-type that is returned (e.g., integer) return -- specifies the values that are to be returned as result of invoking the function SQL function are in fact parameterized views that generalize the regular notion of views by allowing parameters. Module 4 Slides by: Shree Jaswal 52

SQL:2003 added functions that return a relation as a result Example: Return all instructors in a given department create function instructor_of (dept_name char(20)) Usage returns table ( ID varchar(5), name varchar(20), dept_name varchar(20), salary numeric(8,2)) return table (select ID, name, dept_name, salary from instructor where instructor.dept_name = instructor_of.dept_name) select * from table (instructor_of ( Music )) Module 4 Slides by: Shree Jaswal 53

The dept_count function could instead be written as procedure: 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 Procedures can be invoked either from an SQL procedure or from embedded SQL, using the call statement. declare d_count integer; call dept_count_proc( Physics, d_count); Procedures and functions can be invoked also from dynamic SQL SQL:1999 allows more than one function/procedure of the same name (called name overloading), as long as the number of arguments differ, or at least the types of the arguments differ Module 4 Slides by: Shree Jaswal 54