1. Advanced SQL Functions Procedural Constructs Triggers.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

1 Constraints, Triggers and Active Databases Chapter 9.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
Chapter 4B: More Advanced PL/SQL Programming
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
Fundamentals, Design, and Implementation, 9/e Chapter 7 Using SQL in Applications.
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
Introduction to Structured Query Language (SQL)
Advanced Database CS-426 Week 2 – Logic Query Languages, Object Model.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 7-1 David M. Kroenke’s Chapter Seven: SQL for Database Construction and.
CSc340 4a1 Advanced SQL Chapter 5 Accessing SQL from a Programming Language Functions and Procedures Triggers.
Triggers Event handlers in the DBMS. Triggers are event handlers Triggers a executed when an event happens in the DBMS Example events – INSERT, UPDATE.
Stored Procedures, Transactions, and Error-Handling
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Programming using C# Joins SQL Injection Stored Procedures
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
CSE 3330 Database Concepts Stored Procedures. How to create a user CREATE USER.. GRANT PRIVILEGE.
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
Triggers and Stored Procedures in DB 1. Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements.
Chapter 4: Advanced SQL. 4.2Unite International CollegeDatabase Management Systems Chapter 4: Advanced SQL SQL Data Types and Schemas Integrity Constraints.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Advanced SQL: Cursors & Stored Procedures
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Murach’s Oracle SQL and PL/SQL, C16© 2014, Mike Murach & Associates, Inc.Slide 1 Thursday, March 12, 12:30 – 13:30PM. MIDTERM.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basic. What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database.
Advanced Database CS-426 Week 1 - Introduction. Database Management System DBMS contains information about a particular enterprise Collection of interrelated.
CMPE 226 Database Systems October 7 Class Meeting Department of Computer Engineering San Jose State University Fall 2015 Instructor: Ron Mak
Advanced SQL: Triggers & Assertions
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
+ Types of Data IST210 Class Lecture. + What kind of data do you have? Class Schedules Contacts Names Phone Numbers Address Food Specials Movies,
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Chapter 5-2: Advanced SQL. 2 Join Expressions Views Integrity Constraints SQL Data Types and Schemas Authorization Accessing SQL From a Programming Language.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
©Silberschatz, Korth and Sudarshan5.1Database System Concepts - 6 th Edition Procedural Constructs in SQL Chapter 5.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
IT420: Database Management and Organization Triggers and Stored Procedures 24 February 2006 Adina Crăiniceanu
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives How to use the SQL programming language How to use SQL cursors How to create stored.
SQL Triggers, Functions & Stored Procedures Programming Operations.
1 Stored Procedure, Function and Trigger. 2Objectives 1. Database Programming 2. Stored Procedure 3. Function 4. Trigger.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Module 7: Advanced SQL.
7.5 Using Stored-Procedure and Triggers NAME MATRIC NUM GROUP Muhammad Azwan Bin Khairul Anwar CS2305A Muhammad Faiz Bin Badrol Shah CS2305B.
COMP 430 Intro. to Database Systems
Chapter 6: Integrity (and Security)
A Guide to SQL, Seventh Edition
Chapter 5: Advanced SQL.
Instructor: Jason Carter
Chapter 5: Advanced SQL Database System concepts,6th Ed.
Error Handling Summary of the next few pages: Error Handling Cursors.
Chapter 5: Advanced SQL.
Database Processing: David M. Kroenke’s Chapter Seven:
Unit I-2.
Chapter 7 Using SQL in Applications
Chapter 8 Advanced SQL.
Information Management
Chapter 11 Managing Databases with SQL Server 2000
© 2014, Mike Murach & Associates, Inc.
Presentation transcript:

1

Advanced SQL Functions Procedural Constructs Triggers

Procedural Extensions and Stored Procedures SQL provides a module language – Permits definition of procedures in SQL, with if-then- else statements, for and while loops, etc. Stored Procedures – Can store procedures in the database – then execute them using the call statement – permit external applications to operate on the database without knowing about internal details

Functions and Procedures SQL supports functions and procedures Functions/procedures can be written in SQL itself, or in an external programming language. Functions 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 also supports a rich set of imperative constructs, including Loops, if-then-else, assignment

SQL Functions 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 Find the department name and budget of all departments with more that 12 instructors. select dept_name, budget from department where dept_count (dept_name ) > 1

Table Functions SQL:2003 added functions that return a relation as a result Example: Return all accounts owned by a given customer create function instructors_of (dept_name char(20) 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 = instructors_of.dept_name) Usage select * from table (instructors_of (‘Music’))

SQL Procedures 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 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

Procedural Constructs Compound statement: begin … end, – May contain multiple SQL statements between begin and end. – Local variables can be declared within a compound statements While and repeat statements: declare n integer default 0; while n < 10 do set n = n + 1 end while repeat set n = n – 1 until n = 0 end repeat

Procedural Constructs (Cont.) For loop Permits iteration over all results of a query Example: declare n integer default 0; for r as select budget from department where dept_name = ‘Music’ do set n = n - r.budget end for

Procedural Constructs (cont.) Conditional statements (if-then-else) SQL also supports a case statement similar to C case statement Example procedure: registers student after ensuring classroom capacity is not exceeded – Returns 0 on success and -1 if capacity is exceeded – See book for details Signaling of exception conditions, and declaring handlers for exceptions declare out_of_classroom_seats condition declare exit handler for out_of_classroom_seats begin ….. signal out_of_classroom_seats end – The handler here is exit -- causes enclosing begin..end to be exited – Other actions possible on exception

External Language Functions/Procedures SQL:1999 permits the use of functions and procedures written in other languages such as C or C++ Declaring external language procedures and functions create procedure dept_count_proc(in dept_name varchar(20), out count integer) language C external name ’ /usr/avi/bin/dept_count_proc’ create function dept_count(dept_name varchar(20)) returns integer language C external name ‘/usr/avi/bin/dept_count’

External Language Routines (Cont.) Benefits of external language functions/procedures: – more efficient for many operations, and more expressive power. Drawbacks – Code to implement function may need to be loaded into database system and executed in the database system’s address space. risk of accidental corruption of database structures security risk, allowing users access to unauthorized data – There are alternatives, which give good security at the cost of potentially worse performance. – Direct execution in the database system’s space is used when efficiency is more important than security.

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

Triggers Tables can have multiple triggers. The CREATE TRIGGER statement can be defined with the FOR UPDATE, FOR INSERT, or FOR DELETE clauses to target a trigger to a specific class of data modification actions. When FOR UPDATE is specified, the IF UPDATE (column_name) clause can be used to target a trigger to updates affecting a particular column. Types of trigger: – After Trigger – Multiple After Triggers – Instead Of Triggers – Mixing Triggers Type

Create Trigger Example: we want to send an to the Sales Manager when an order is entered whose priority is high. When SQL is used to insert the Orders row, a trigger is used to determine the OrderPriority and send the when the criteria is met. CREATE TABLE Orders (Ord_ID int IDENTITY, Ord_Priority varchar(10)) go CREATE TRIGGER tr_Orders_INSERT ON Orders FOR INSERT AS IF (SELECT COUNT(*) FROM inserted WHERE Ord_Priority = 'High') = 1 BEGIN PRINT ' Code Goes Here' END go INSERT Orders (Ord_Priority) VALUES ('High')

Update Trigger An UPDATE trigger is used to perform an action after an update is made on a table CREATE TRIGGER tr_Orders_UPDATE ON Orders AFTER UPDATE AS --Make sure Priority was changed IF NOT UPDATE(Ord_Priority) RETURN --Determine if Priority was changed to high IF EXISTS (SELECT * FROM inserted a JOIN deleted b ON a.Ord_ID=b.Ord_ID WHERE b.Ord_Priority <> 'High' AND a.Ord_Priority = 'High') BEGIN tinyint = (SELECT COUNT(*) FROM inserted a JOIN deleted b ON a.Ord_ID=b.Ord_ID WHERE b.Ord_Priority <> 'High' AND a.Ord_Priority = 'High') PRINT as varchar(3))+' row(s) where changed to a priority of High' END go

Delete Trigger The example here simply counts the number of rows in the deleted table to see how many had a priority of high CREATE TRIGGER tr_Orders_DELETE ON Orders AFTER DELETE AS --Determine if Order with a Priority of High was deleted IF EXISTS (SELECT * FROM deleted WHERE Ord_Priority = 'High') BEGIN tinyint = (SELECT * FROM deleted WHERE Ord_Priority = 'High') PRINT as varchar(3))+' row(s) where deleted whose priority was High' END go

Instead of Trigger An INSTEAD OF Trigger is used to perform an action instead of the one that caused the trigger to be fired. If we have an INSTEAD OF INSERT trigger defined on a table and an INSERT is executed. A row is not added to the table, but the code in the trigger is fired. CREATE TRIGGER tr_Orders_INSERT_InsteadOf ON Orders INSTEAD OF INSERT AS PRINT 'Updateable Views are Messy' go

Instead of Trigger INSTEAD-OF triggers are very powerful objects in SQL Server. They allow the developer to divert the database engine to do something different than what the user is trying to do. An example of this would be to add an INSTEAD-OF trigger to any table in your database that rolls back transactions on tables that you do not want modified. We must be careful when using this method because the INSTEAD-OF trigger will need to be disabled before any specified modifications can occur to this table.

After versus Instead of Triggers When should we use an AFTER trigger vs. INSTEAD OF trigger? If the data modification will always happen - AFTER trigger. If the data modification will never happen - INSTEAD OF trigger. If the data modification will happen more often than the alternate code - AFTER trigger. If the data modification will happen less often than the alternate code - INSTEAD OF trigger.