1 Minggu 6, Pertemuan 11 Programmatic SQL Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0.

Slides:



Advertisements
Similar presentations
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives u How to use the SQL programming language u How to use SQL cursors u How to create.
Advertisements

BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL.
Embedded SQL (Cont.) Pertemuan 10 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Dynamic SQL Pertemuan 11 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Embedded SQL John Ortiz. Lecture 15Embedded SQL2 Why Isn’t Interactive SQL Enough?  How to do this using interactive SQL?  Print a well-formatted transcript.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Murali Mani SQL with other Programming Languages.
1 Minggu 4, Pertemuan 8 SQL: Data Manipulation (Cont.) Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0.
Embedded SQL Pertemuan 9 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
1 Pertemuan 20 Run-Time Environment Matakuliah: T0174 / Teknik Kompilasi Tahun: 2005 Versi: 1/6.
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.
DB2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/DB01/003 Version No:2.0a Session Plan SPUFI Hands On Introduction to Embedded SQL DCLGEN.
Jump-Start Embedded SQL into RPG Presented by: Robert Arce.
Advanced Database CS-426 Week 2 – Logic Query Languages, Object Model.
1 Section 6 Embedded SQL. 6-2 CA306 Embedded SQL Section Content 6.1Embedded SQL 6.2Java Database Connectivity 6.3Web Databases.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
1 No class Thurs. Oct. 2 E-day Exam 1 Thurs. Oct. 9 HW3 Oct. 2 to –Available Oct 2 only until 2 pm.
Dinamic SQL & Cursor. Why Dinamic SQL ? Sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
Converting To Anthony Tichonoff Florida Hospital MIS January 2007 With Ease Multi-Row Fetch.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Advanced SQL: Cursors & Stored Procedures
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
SQL in a Programming Environment CIS 4301 Lecture Notes Lecture /11/2006.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
1 CS 430 Database Theory Winter 2005 Lecture 14: Additional SQL Topics.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Variables and control statements in PL\SQL Chapter 10.
Dr Gordon Russell, Napier University Unit Embedde SQL - V2.0 1 Embedded SQL Unit 5.1.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
Chapter 8 Embedded SQL.
Retrieving Data in PL/SQL. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Recognize the SQL statements that can.
In this module, we will design a program to work with the PROJECT table, learning to insert a new project into the table, to delete one or more projects.
Lu Wei1 Outline Introduction Basic SQL Setting Up and Using PostgreSQL Advanced SQL Embeded SQL.
RETRIEVE A NO. OF ROWS ¦ Declare a cursor ¦ Open the cursor ¦ Fetch rows of data ¦ Stop fetching rows ¦ Close the cursor.
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.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
1 Minggu 6, Pertemuan 12 Query Processing Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
Chapter 4 An Introduction to SQL.
1st Semester, 2017 Sanghyun Park
Introduction to Database Systems, CS420
A Guide to SQL, Seventh Edition
SQL : Data Manipulation Pertemuan 07 s/d 08
Interacting with the Oracle Server
Interacting with the Oracle Server
Chapter 5: Advanced SQL Database System concepts,6th Ed.
Minggu 5, Pertemuan 9 SQL: Data Definition
Database Management Systems 2
REF Cursors.
CPSC-310 Database Systems
Introduction to Database
variables and control statements in PL\SQL
Unit I-2.
Chapter 8 Advanced SQL.
Chapter 8 Advanced SQL Pearson Education © 2009.
Presentation transcript:

1 Minggu 6, Pertemuan 11 Programmatic SQL Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0

2 Learning Outcomes Pada akhir pertemuan ini, diharapkan mahasiswa dapat mendemonstrasikan bagaimana SQL dapat diintegrasikan di dalam high level programming language (C3)

3 Outline Materi How SQL statements can be embedded in high-level programming languages. Difference between static and dynamic embedded SQL. How to write programs that use static embedded SQL. How to write programs that use dynamic embedded SQL.

4 Embedded SQL SQL can be embedded in high-level procedural language. In many cases, language is identical although SELECT statement differs. Two types of programmatic SQL: –Embedded SQL statements. SQL supports Ada, C, COBOL, FORTRAN, MUMPS, Pascal, and PL/1. –Application program interface (API).

5 Example CREATE TABLE EXEC SQL CREATE TABLE Viewing( propertyNo VARCHAR2(5) NOT NULL, clientNo VARCHAR2(5) NOT NULL, viewDate DATE NOT NULL, comment VARCHAR2(40)); if (sqlca.sqlcode >= 0) printf(“Creation successful\n”);

6 Embedded SQL Embedded SQL starts with identifier, usually EXEC SQL [ in MUMPS]. Ends with terminator dependent on host language: –Ada, ‘C’, and PL/1: terminator is semicolon (;) –COBOL: terminator is END-EXEC –Fortran: ends when no more continuation lines. Embedded SQL can appear anywhere an executable host language statement can appear.

7 SQL Communications Area (SQLCA) Used to report runtime errors to the application program. Most important part is SQLCODE variable: 0 - statement executed successfully; < 0 - an error occurred; > 0 - statement executed successfully, but an exception occurred, such as no more rows returned by SELECT.

8 SQLCA for Oracle

9 WHENEVER Statement Every embedded SQL statement can potentially generate an error. WHENEVER is directive to precompiler to generate code to handle errors after every SQL statement: EXEC SQL WHENEVER

10 WHENEVER Statement condition can be: SQLERROR - generate code to handle errors (SQLCODE < 0). SQLWARNING - generate code to handle warnings. NOT FOUND - generate code to handle specific warning that a retrieval operation has found no more records.

11 WHENEVER Statement action can be: CONTINUE - ignore condition and proceed to next statement. DO - transfer control to an error handling function. DO BREAK - place an actual “break” statement in the program. DO CONTINUE - place an actual “continue” statement in the program. GOTO label or GO TO label - transfer control to specified label. STOP - rollback all uncommitted work and terminate the program.

12 WHENEVER Statement EXEC SQL WHENEVER SQLERROR GOTO error1; EXEC SQL INSERT INTO Viewing VALUES (‘CR76’, ‘PA14’, ‘12-May-2001’, ‘Not enough space’); would be converted to: EXEC SQL INSERT INTO Viewing VALUES (‘CR76’, ‘PA14’, ‘12-May-2001’, ‘Not enough space’); if (sqlca.sqlcode < 0) goto error1;

13 Host Language Variables Program variable declared in host language. Used in embedded SQL to transfer data from database into program and vice versa. Can be used anywhere a constant can appear. Cannot be used to represent database objects, such as table names or column names. To use host variable, prefix it by a colon (:).

14 Host Language Variables EXEC SQL UPDATE Staff SET salary = salary + :increment WHERE staffNo = ‘SL21’; Need to declare host language variables to SQL, as well as to host language: EXEC SQL BEGIN DECLARE SECTION; float increment; EXEC SQL END DECLARE SECTION;

15 Indicator Variables Indicates presence of null: 0 associated host variable contains valid value. <0associated host variable should be assumed to contain a null; actual contents of host variable irrelevant. >0 associated host variable contains valid value. Used immediately following associated host variable with a colon (:) separating two variables.

16 Indicator Variables - Example EXEC SQL BEGIN DECLARE SECTION; charaddress[51]; shortaddressInd; EXEC SQL END DECLARE SECTION; addressInd = -1; EXEC SQL UPDATE PrivateOwner SET address = :address :addressInd WHERE ownerNo = ‘CO21’;

17 Singleton SELECT - Retrieves Single Row EXEC SQL SELECT fName, lName, address INTO :firstName, :lastName, :address :addressInd FROM PrivateOwner WHERE ownerNo = ‘CO21’; Must be 1:1 correspondence between expressions in SELECT list and host variables in INTO clause. If successful, SQLCODE set to 0; if there are no rows that satisfies WHERE, SQLCODE set to NOT FOUND.

18 Cursors If query can return arbitrary number of rows, need to use cursors. Cursor allows host language to access rows of query one at a time. Cursor acts as a pointer to a row of query result. Cursor can be advanced by one to access next row. Cursor must be declared and opened before it can be used and it must be closed to deactivate it after it is no longer required.

19 Cursors - DECLARE CURSOR Once opened, rows of query result can be retrieved one at a time using FETCH: EXEC SQL DECLARE propertyCursor CURSOR FOR SELECT propertyNo, street, city FROM PropertyForRent WHERE staffNo = ‘SL41’;

20 Cursors - OPEN OPEN statement opens specified cursor and positions it before first row of query result: EXEC SQL OPEN propertyCursor;

21 Cursors - FETCH and CLOSE FETCH retrieves next row of query result table: EXEC SQL FETCH propertyCursor INTO :propertyNo, :street, :city FETCH is usually placed in a loop. When there are no more rows to be returned, SQLCODE is set to NOT FOUND. EXEC SQL CLOSE propertyCursor;

22 ISO Standard for Embedded SQL Standard does not recognize SQLWARNING of WHENEVER statement. Standard does not mention an SQLCA. It does, however, recognize the integer variable SQLCODE, although this is a deprecated feature that is supported only for compatibility with earlier versions of the standard. Instead, defines a character string SQLSTATE parameter, comprising a two- character class code followed by a three- character subclass code.

23 ISO Standard for Embedded SQL Standard specifies definition and processing of cursors slightly differently from that presented above. ISO DECLARE CURSOR is: EXEC SQL DECLARE cursorName [INSENSITIVE] [SCROLL] CURSOR FOR selectStatement [FOR {READ ONLY | UPDATE [OF columnNameList]}]

24 ISO Standard for Embedded SQL FETCH statement: EXEC SQL FETCH [[fetchOrientation] FROM] cursorName INTO hostVariable [,... ] fetchOrientation can be one of: –NEXT –PRIOR –FIRST –LAST –ABSOLUTE –RELATIVE

25 Dynamic Embedded SQL With static embedded SQL, cannot use host variables where database object names required. Dynamic SQL allows this. Idea is to place complete SQL statement in a host variable, which is passed to DBMS to be executed. If SQL statements do not involve multi-row queries, use EXECUTE IMMEDIATE statement: EXEC SQL EXECUTE IMMEDIATE [hostVariable | stringLiteral]

26 Dynamic Embedded SQL For example: sprintf(buffer, “UPDATE Staff SET salary = salary + %f WHERE staffNo = ‘SL21’ ”, increment); EXEC SQL EXECUTE IMMEDIATE :buffer;

27 PREPARE and EXECUTE DBMS must parse, validate, and optimize each EXECUTE IMMEDIATE statement, build execution plan, and execute plan. OK if SQL statement is only executed once in program; otherwise inefficient. Dynamic SQL provides alternative: PREPARE and EXECUTE. PREPARE tells DBMS to ready dynamically built statement for later execution.

28 PREPARE and EXECUTE Prepared statement assigned name. When statement is subsequently executed, program need only specify this name: EXEC SQL PREPARE statementName FROM [hostVariable | stringLiteral] EXEC SQL EXECUTE statementName [ USING hostVariable [indicatorVariable] [,...] | USING DESCRIPTOR descriptorName ]

29 Parameter Markers USING allows portions of prepared statement to be unspecified, replaced by placeholders (parameter markers). Placeholder can appear anywhere in hostVariable or stringLiteral of PREPARE that constant can appear. Tells DBMS value will be supplied later, in EXECUTE statement.

30 Placeholders sprintf(buffer, “UPDATE Staff SET salary = :sal WHERE staffNo = :sn”); EXEC SQL PREPARE stmt FROM :buffer; EXEC SQL EXECUTE stmt USING :newSalary, :staffNo; sal and sn are placeholders.

31 Static versus Dynamic SQL

32 SQL Descriptor Area (SQLDA) Alternative way to pass parameters to EXECUTE statement is through SQLDA. Used when number of parameters and their data types unknown when statement formulated. SQLDA can also be used to dynamically retrieve data when do not know number of columns to be retrieved or the types of the columns.

33 SQLDA for Oracle

34 Retrieving Data Using Dynamic SQL Again, use cursors to retrieve data from a query result table that has an arbitrary number of rows. EXEC SQL DECLARE cursorName CURSOR FOR selectStatement EXEC SQL OPEN cursorName [FOR READONLY] {USING hostVariable [indicatorVariable] [,...] | USING DESCRIPTOR descriptorName } EXEC SQL FETCH cursorName {INTO hostVariable [indicatorVariable] [,...] | USING DESCRIPTOR descriptorName } EXEC SQL CLOSE cursorName

35 Retrieving Data Using Dynamic SQL OPEN allows values for placeholders to be substituted using one or more hostVariables in: –USING clause or –passing values via descriptorName (SQLDA) in a USING DESCRIPTOR clause. Main difference is with FETCH, which now uses descriptorName to receive rows of query result table (or one or more hostVariables/ indicatorVariables).

36 Retrieving Data Using Dynamic SQL Before FETCH, program must provide data areas to receive retrieved data and indicator variables. Basic steps for dynamic SQL statement are: (1) Declare host string in DECLARE SECTION to hold text of the query. (2) Declare a select SQLDA and, if required, a bind SQLDA. (3) Allocate storage space for the SQLDA(s). (4) Set maximum number of columns in select SQLDA and, if query can have placeholders, maximum number of placeholders in bind SQLDA.

37 Retrieving Data Using Dynamic SQL (5) Put the query text into the host string. (6) PREPARE the query from the host string. (7) DECLARE a cursor for the query. (8) If the query can have placeholders: (a)DESCRIBE bind variables into bind SQLDA. (b)Reset number of placeholders to number actually found by DESCRIBE. (c)Get values and allocate storage space for bind variables found by DESCRIBE. (9) OPEN cursor USING the bind SQLDA, or if no bind SQLDA has been used, USING the select SQLDA.

38 Retrieving Data Using Dynamic SQL (10) DESCRIBE the column list INTO the select SQLDA. (11) Reset number of column list items to number actually found by DESCRIBE. (12) Reset length and data type of each column list item. (13) FETCH each row from database into allocated data buffers pointed to by the select SQLDA and process it, as appropriate. (14) Deallocate the storage space used for the column list items, placeholders, indicator variables, and SQLDAs. (15) CLOSE the cursor.