SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:



Similar documents
SQL Tables, Keys, Views, Indexes

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Real SQL Programming. Persistent Stored Modules (PSM) PL/SQL Embedded SQL

Programming Database lectures for mathema

SQL NULL s, Constraints, Triggers

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

In This Lecture. Security and Integrity. Database Security. DBMS Security Support. Privileges in SQL. Permissions and Privilege.

CS346: Database Programming.

Real SQL Programming. Embedded SQL Call-Level Interface Java Database Connectivity

A basic create statement for a simple student table would look like the following.

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

SQL and Programming Languages. SQL in Programming Languages. Applications. Approaches

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

PL/SQL (Cont d) Let s start with the mail_order database, shown here:

14 Triggers / Embedded SQL

Real SQL Programming 1

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications

Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

Persistent Stored Modules (Stored Procedures) : PSM

Oracle Database: SQL and PL/SQL Fundamentals

Week 1 Part 1: An Introduction to Database Systems. Databases and DBMSs. Why Use a DBMS? Why Study Databases??

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

SQL is capable in manipulating relational data SQL is not good for many other tasks

PL/SQL. Database Procedural Programming PL/SQL and Embedded SQL. Procedures and Functions

Database Programming with PL/SQL: Learning Objectives

Oracle For Beginners Page : 1

Migrate Topaz databases from One Server to Another

An Introduction to PL/SQL. Mehdi Azarmi

Oracle SQL, introduced in the previous chapter, is not a language that can be

Creating PL/SQL Blocks. Copyright 2007, Oracle. All rights reserved.

Embedded SQL programming

COSC344 Database Theory and Applications. Java and SQL. Lecture 12

Darshan Institute of Engineering & Technology PL_SQL

More SQL: Assertions, Views, and Programming Techniques

Lecture 6. SQL, Logical DB Design

There are five fields or columns, with names and types as shown above.

Oracle Database 12c: Introduction to SQL Ed 1.1

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

Creating Customized Oracle Forms

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

EECS 647: Introduction to Database Systems

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

CS2Bh: Current Technologies. Introduction to XML and Relational Databases. Introduction to Databases. Why databases? Why not use XML?

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Introduction to SQL for Data Scientists

Oracle PL/SQL Language. CIS 331: Introduction to Database Systems

Developing SQL and PL/SQL with JDeveloper

Oracle Data Redaction is Broken

The Relational Model. Why Study the Relational Model?

CSC 443 Database Management Systems. The SQL Programming Language

5.1 Database Schema Schema Generation in SQL

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Oracle SQL. Course Summary. Duration. Objectives

SQL and programming languages

When an exception occur a message which explains its cause is received. PL/SQL Exception message consists of three parts.

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

Relational Database Design: FD s & BCNF

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle PL/SQL Injection

Introduction to PL/SQL Programming

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Database Management Systems. Chapter 1

ERserver. DB2 Universal Database for iseries SQL Programming with Host Languages. iseries. Version 5

The Sins of SQL Programming that send the DB to Upgrade Purgatory Abel Macias. 1 Copyright 2011, Oracle and/or its affiliates. All rights reserved.

Databases 2011 The Relational Model and SQL

Oracle 10g PL/SQL Training

CS143 Notes: Views & Authorization

Oracle Database 10g: Introduction to SQL

Oracle Database: Program with PL/SQL

Oracle Database: Introduction to SQL

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Oracle Database: Introduction to SQL

Database Design and Programming

CS 241 Data Organization Coding Standards

Overview. Introduction to Database Systems. Motivation... Motivation: how do we store lots of data?

Objectives of SQL. Terminology for Relational Model. Introduction to SQL

Maintaining Stored Procedures in Database Application

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

COMS20700 DATABASES 13 PL/SQL. COMS20700 Databases Dr. Essam Ghadafi

1 File Processing Systems

Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement

PL/SQL: Introduction. Overview. Anonymous Blocks and Basic Language Features

A Brief Introduction to MySQL

Basic Concepts of Database Systems

types, but key declarations and constraints Similar CREATE X commands for other schema ëdrop X name" deletes the created element of beer VARCHARè20è,

Optimizing with Open Source Technology Postgres

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6

Database Extension 1.5 ez Publish Extension Manual

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

Transcription:

CS145 Lecture Notes #10 SQL Programming Example schema: CREATE TABLE Student (SID INTEGER PRIMARY KEY, name CHAR(30), age INTEGER, GPA FLOAT); CREATE TABLE Take (SID INTEGER, CID CHAR(10), PRIMARY KEY(SID, CID)); CREATE TABLE Course (CID CHAR(10) PRIMARY KEY, title VARCHAR(100) UNIQUE); Motivation Pros and cons of SQL: Very high-level, possible to optimize Not tuned to support general-purpose computation Oracle as a calculator? SELECT 142857*3 FROM DUAL; Strictly less expressive than general-purpose languages SQL2 has no recursion and cannot even compute factorial! Solutions: Augment SQL: Oracle s PL/SQL Use SQL together with a general-purpose programming language: embedded SQL, dynamic SQL Oracle PL/SQL Basics Rough form of a PL/SQL program: section is optional and RUN end the program and execute it Jun Yang 1 CS145 Spring 1999

Example: go through students 142 857 and set all GPA s under 40 to 40 thissid StudentSID%TYPE; thisgpa StudentGPA%TYPE; thissid := 142; LOOP EXIT WHEN (thissid > 857); SELECT GPA INTO thisgpa FROM Student WHERE SID = thissid; IF (thisgpa < 40) THEN UPDATE Student SET GPA = 40 WHERE SID = thissid; END IF; thissid := thissid + 1; END LOOP; Basic features: Local variable: Use %TYPE to match its type to a column in the schema Use := for assignment; = for comparison Branch: IF () THEN ELSE END IF; Loop: LOOP EXIT WHEN (); END LOOP; The usual data modification statements: INSERT, DELETE, UPDATE Single-row SELECT: SELECT INTO FROM ; Oracle raises an exception if SELECT returns no rows or more than one row Cursors Inside a PL/SQL program, the result of a SELECT must go somewhere: If SELECT returns one row, it can go INTO a variable What if SELECT returns multiple rows? Cursor: a variable that runs through the result of a SELECT, row by row Declare by: CURSOR IS ; Use inside a cursor loop: Fetch one result row at a time: FETCH INTO ; Break the loop when there are no more rows to return: EXIT WHEN %NOTFOUND; OPEN/CLOSE before/after use Jun Yang 2 CS145 Spring 1999

If cursor is over a single table and has no aggregates or DISTINCT, we can also modify data through the cursor: Follow the declaration by FOR UPDATE Use WHERE CURRENT OF in DELETE or UPDATE Example: go through all CS145 students and set all GPA s under 40 to 40! Note it is possible to declare a row type in Oracle thisstudent Student%ROWTYPE; CURSOR CS145Student IS SELECT * FROM Student WHERE SID IN (SELECT SID FROM Take WHERE CID = CS145 ) FOR UPDATE; OPEN CS145Student; LOOP FETCH CS145Student INTO thisstudent; EXIT WHEN (CS145Student%NOTFOUND); IF (thisstudentgpa < 40) THEN UPDATE Student SET GPA = 40 WHERE CURRENT OF CS145Student; END IF; END LOOP; CLOSE CS145Student; Stored Procedures Creating a PL/SQL stored procedure: CREATE PROCEDURE ( ) AS The RUN above creates the procedure, but does not execute it Running the procedure inside a PL/SQL program: ( ); Jun Yang 3 CS145 Spring 1999

Dropping the procedure: DROP PROCEDURE ; Example: a procedure to enroll students in CS145 CREATE PROCEDURE CS145Enroll (thissid IN TakeSID%TYPE) AS INSERT INTO Take VALUES(thisSID, CS145 ); Example: students 142 and 857 enroll in CS145 CS145Enroll(142); CS145Enroll(857); Embedded SQL Instead of making SQL do more, embed it into a general-purpose programming language (C in our examples): (1) Host program with special SQL directives and commands Goes through a special DBMS preprocessor to produce: (2) Host program with special DBMS function calls Gets compiled and linked with special DBMS library to produce: (3) Executable code that communicates with the DBMS Main issues in embedding SQL within a program: Which statements are SQL? Those introduced with EXEC SQL How are values passed from the program into SQL commands? Shared Variables: variables that are accessible to both SQL and the host language In C, variables are used normally In SQL, they must be preceded by a colon How are results of SQL queries returned into program variables? If query returns a single row, use SELECT INTO If query returns many rows, use a cursor Similar to PL/SQL cursors, with minor syntactic differences In Oracle, WHENEVER can be used to break cursor loops Jun Yang 4 CS145 Spring 1999

Example: go through all CS145 students and change all GPA s EXEC SQL SECTION; int thissid; float thisgpa; EXEC SQL END SECTION; EXEC SQL CS145Student CURSOR FOR SELECT SID, GPA FROM Student WHERE SID IN (SELECT SID FROM Take WHERE CID = CS145 ) FOR UPDATE; EXEC SQL OPEN CS145Student; EXEC SQL WHENEVER NOT FOUND DO break; while (1) { EXEC SQL FETCH CS145Student INTO :thissid, :thisgpa; printf("sid %d current GPA %f\n", thissid, thisgpa); printf("enter new GPA: "); scanf("%f", &thisgpa); EXEC SQL UPDATE Student SET GPA = :thisgpa WHERE CURRENT OF CS145Student; } EXEC SQL CLOSE CS145Student; Dynamic SQL Embedded SQL is fine for fixed applications (eg, a program used by the registrar to enroll students in classes) But we cannot use it to write a program like sqlplus, because we do not know in advance what SQL statements the user will enter Two special statements in embedded SQL which make it dynamic: PREPARE EXECUTE Example: let s write our own sqlplus! EXEC SQL SECTION; char query[max_query_length]; EXEC SQL END SECTION; while (1) { /* issue SQL> prompt */ /* read user input into query */ EXEC SQL PREPARE q FROM :query; EXEC SQL EXECUTE q; } Jun Yang 5 CS145 Spring 1999