Programming the Database

Similar documents
Active Databases Part 1: Introduction CS561

Slides by: Ms. Shree Jaswal

COSC344 Database Theory and Applications. Lecture 11 Triggers

CS2 Current Technologies Note 1 CS2Bh

King Fahd University of Petroleum and Minerals

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

Database System Concepts"

Indexes (continued) Customer table with record numbers. Source: Concepts of Database Management

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

1Z0-144 Q&As Oracle Database 11g: Program with PL/ SQL

Department of Computer Science and Information Systems, College of Business and Technology, Morehead State University

Introduction. Introduction to Oracle: SQL and PL/SQL

Chapter 14. Active Databases. Database Systems(Part 2) p. 200/286

Part III. Data Modelling. Marc H. Scholl (DBIS, Uni KN) Information Management Winter 2007/08 1

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

Stored Procedures in MYSQL

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

COMP 430 Intro. to Database Systems. Encapsulating SQL code

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

DATABASE DESIGN - 1DL400

Creating and Managing Tables Schedule: Timing Topic

Instructor: Craig Duckett. Lecture 14: Tuesday, May 15 th, 2018 Stored Procedures (SQL Server) and MySQL

Domain Constraints Referential Integrity Assertions Triggers. Authorization Authorization in SQL

Lecture 08. Spring 2018 Borough of Manhattan Community College

CS2 Current Technologies Lecture 2: SQL Programming Basics

Actual4Test. Actual4test - actual test exam dumps-pass for IT exams

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

Sample Question Paper

5 Integrity Constraints and Triggers

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries

Creating SQL Tables and using Data Types

Oracle Exam 1z0-144 Oracle Database 11g: Program with PL/SQL Version: 8.5 [ Total Questions: 103 ]

Database System Concepts

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

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Sample Test #1 Questions

STORED PROCEDURE AND TRIGGERS

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

To understand the concept of candidate and primary keys and their application in table creation.

An Introduction to Stored Procedures in MySQL 5 by Federico Leven6 Apr 2011

SQL. SQL DDL Statements

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

Real-World Performance Training SQL Introduction

Database implementation Further SQL

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

Introduction to the Structured Query Language [ SQL ] (Significant Concepts)

Database Management Systems Triggers

SQL Structured Query Language Introduction

Database Programming with PL/SQL

SQL Stored Programs. You Can Not Do Everything in SQL SQL/PSM Cursors Recursion Triggers. Niklas Fors Stored Programs 1 / 21

Programming in Oracle with PL/SQL. Procedural Language Extension to SQL

NULLs & Outer Joins. Objectives of the Lecture :

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

Database Modelling. Lecture 4 (b): Database Integrity, Keys & Constraints. Akhtar Ali 10/14/2014 1

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

Oracle 1Z Oracle Database 12c: Advanced PL/SQL.

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

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

ITCS Implementation. Jing Yang 2010 Fall. Class 14: Introduction to SQL Programming Techniques (Ch13) Outline

SQL STORED ROUTINES. CS121: Relational Databases Fall 2017 Lecture 9

Amendments & Transactions

Basic SQL. Basic SQL. Basic SQL

CS2300: File Structures and Introduction to Database Systems

Lab # 4. Data Definition Language (DDL)

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

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

Overview of PL/SQL. About PL/SQL. PL/SQL Environment. Benefits of PL/SQL. Integration

Triggers and Events. Kathleen Durant PhD CS 3200

Manual Trigger Sql Server 2008 Update Inserted Rows

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

Oracle Database: Program with PL/SQL

Module 9: Managing Schema Objects

Database Modelling. Lecture 5 Part 1: Updating Database 1/6/2015 1

An Introduction to Structured Query Language

Oracle Database: Program with PL/SQL Ed 2

An Introduction to Structured Query Language

Lecture 7 Stored procedure

IBM DB2 9.7 SQL Procedure Developer.

An Introduction to Structured Query Language

Manual Trigger Sql Server 2008 Examples Insert Update

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

Assorted Topics Stored Procedures and Triggers Pg 1

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

Objectives. After completing this lesson, you should be able to do the following:

Database Technology. Topic 6: Triggers and Stored Procedures

Vendor: Oracle. Exam Code: 1Z Exam Name: Oracle Database 11g: Program with PL/ SQL. Version: Demo

CSE 530A. Inheritance and Partitioning. Washington University Fall 2013

Database Application Programs PL/SQL, Java and the Web

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

The Relational Model. Chapter 3

Extension to SQL: View, Triggers, Transaction. SS Chung

1Z Oracle Database 11g - Program with PL/SQL Exam Summary Syllabus Questions

Lesson 13 Transcript: User-Defined Functions

Oracle Database: Program with PL/SQL

MIS Database Systems.

SQL Data Definition and Data Manipulation Languages (DDL and DML)

BIS Database Management Systems.

Databases. Relational Model, Algebra and operations. How do we model and manipulate complex data structures inside a computer system? Until

An Introduction to Structured Query Language

Transcription:

Programming the Database Today s Lecture 1. Stored Procedures 2. Functions BBM471 Database Management Systems Dr. Fuat Akal akal@hacettepe.edu.tr 3. Cursors 4. Triggers 5. Dynamic SQL 2 Stored Procedures Example Stored Procedure: Definition 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 (I refer to MySQL in this presentation): Create Procedure <proc-name> (param_spec 1, param_spec 2,, param_spec n ) 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 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 deptsaltable 4

Create the Stored Procedure Call the Stored Procedure 1. Change the delimiter (i.e., terminating character) of SQL statement from semicolon (;) to something else (e.g., //) 2. Define a procedure called updatesalary which takes as input a department number. 3. The body of the procedure is an SQL command to update the totalsalary column of the deptsal table. 4. Terminate the procedure definition using the delimiter you had defined in step 1 (//) 5. Change the delimiter back to semicolon (;) 5 6 Debugging a Stored Procedure Using a select statement SELECT Comment ; -- Put the literal Comment out to console Insert into a table Putting the current time and date stamp into a column with the comment. Programming Structures Google for XXX reference manual XXX à MySQL, SQL Server, Oracle, Sybase, etc. e.g., to locate IF statement, click on Functions and Operators Control Flow Functions Log messages to an output file Select <time_stamp>, Comment into outfile <file_name> ; Which might be blocked by the security mechanism. https://dev.mysql.com/doc/refman/8.0/en/ 7 8

Database Cursors A database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. A cursor can't be used by itself. It is an essential component in stored procedures. Example Cursor Use cursor to iterate the rows Drop the old procedure 9 10 Cursor Example (Oracle Pl/SQL) DECLARE Pi constant NUMBER(8,7) := 3.1415926; area NUMBER(14,2); cursor rad_cursor is select * from RAD_VALS; rad_val rad_cursor%rowtype; BEGIN open rad_cursor; fetch rad_cursor into rad_val; area:=pi*power(rad_val.radius,2); insert into AREAS values (rad_val.radius, area); close rad_cursor; END; Rad_cursor f e t c h Rad_val RAD_VALS radius 3 6 8 AREAS Radius Area 3 28.27 Select For Update Cursors can also be used to perform updates cursor <cname> is <select-statement> for update; Select statement should involve only one database table update <table-name> set <set-clause> where current of <cname>; delete from < table-name > where current of <cname>; 11 12

Functions Example Function Functions return some value and are declared using the following syntax: function <function-name> (param_spec 1,, param_spec k ) returns <return_type> [not] deterministic Begin -- execution code end; where param_spec is: [in out in out] <param_name> <param_type> 13 14 Function Call Triggers 15

What is a Trigger? 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. Trigger vs. Vendors Available in most enterprise DBMSs (Oracle, IBM DB2, MS SQL server) and some public domain DBMSs (Postgres, MySQL) Some vendor DBMS permit native extensions to SQL for specifying the triggers e.g. PL/SQL in Oracle, Transact SQL in MS SQL Server Some DBMS also allow use of general purpose programming language instead of SQL e.g. Java in Oracle, C#/VB in SQL Server Some DBMS extend the triggers beyond tables for example also to views as in Oracle 17 18 Types of Triggers How many times should the trigger body execute when the triggering event takes place? Per statement: the trigger body executes once for the triggering event. This is the default. For each row: the trigger body executes once for each row affected by the triggering event. When the trigger can be fired Relative to the execution of an SQL DML statement (before or after or instead of it) Exactly in a situation depending on specific system resources (e.g. signal from the system clock, expiring timer, exhausting memory) Triggering Events and Actions in SQL Triggering event can be insert, delete or update 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 Triggers can be activated before an event, which can serve as extra constraints. E.g. convert blanks to null. create trigger setnull-trigger before update on r referencing new row as nrow for each row when nrow.phone-number = set nrow.phone-number = null 19 20

Firing Sequence of Database Triggers on a Single Row Firing Sequence of Database Triggers on Multiple Rows DEPT table DEPTNO DNAME 10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON BEFORE statement trigger BEFORE row trigger AFTER row trigger EMP table EMPNO ENAME 7839 KING 7698 BLAKE 7788 SMITH DEPTNO 30 30 30 BEFORE statement trigger BEFORE row trigger AFTER row trigger BEFORE row trigger AFTER row trigger BEFORE row trigger AFTER row trigger AFTER statement trigger AFTER statement trigger 21 22 Trigger Example - 1 Trigger Example - 1 We want to create a trigger to update the total salary of a department when a new employee is hired 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 23 24

Trigger Example - 1 Trigger Example - 2 A trigger to update the total salary of a department when an employee tuple is modified: totalsalary increases by 90K totalsalary did not change 25 26 Trigger Example - 2 Trigger Example - 3 A trigger to update the total salary of a department when an employee tuple is deleted: 27 28

Trigger Example - 3 Using Database Triggers for Information Processing Auditing Table Operations each time a table is accessed auditing information is recorded against it Tracking Record Value Changes each time a record value is changed the previous value is recorded Protecting Database Referential Integrity: if foreign key points to changing records referential integrity must be maintained Maintenance of Semantic Integrity e.g. when the factory is closed, all employees should become unemployed Storing Derived Data e.g. the number of items in the trolley should correspond to the current session selection Security Access Control e.g. checking user privileges when accessing sensitive information 29 30 When Not To Use Triggers Dynamic SQL 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 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 Sometimes you need to operate against a table or columns that are not known at compile time. CREATE DEFINER=`root`@`localhost` PROCEDURE `dynamic`(in tablename varchar(40)) begin end set @statement = concat('select * from ', tablename); prepare stmt from @statement; execute stmt; set @statement = concat('select count(*) from ', tablename, ' into @count'); prepare stmt from @statement; execute stmt; select concat('count was: ', @count, ' from table: ', tablename); deallocate prepare stmt; 31 32

Summary It is not possible to perform all tasks by using a single SQL statement Sometimes you need to implement the business logic at the database side There you can use stored procedures, functions, cursors, trigger, etc. There are few more structures not covered in this lecture Acknowledgements The course material used for this lecture is mostly taken and/or adopted from: www.cse.msu.edu/~pramanik/teaching/courses/cse480/14s/lectures/ 12/lecture13.ppt by Sakti Pramanik at Michigan State University Database System Concepts, Avi Silberschatz, Henry F. Korth, S. Sudarshan 33 34