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.

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to Structured Query Language (SQL)
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
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.
Chapter 4B: More Advanced PL/SQL Programming
Introduction to Structured Query Language (SQL)
Chapter 7 Advanced SQL Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
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)
Chapter 5 Data Manipulation and Transaction Control Oracle 10g: SQL
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Session Title: Using SQL and PL/SQL for Queries and Reporting Presented By: Stephen Frederic Institution: IHL September 16, 2013.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Agenda Journalling More Embedded SQL. Journalling.
SQL Training Procedures & Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. DB Procedures & Functions Procedures and Functions.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Stored Procedures, Transactions, and Error-Handling
Program with PL/SQL. Interacting with the Oracle Server.
PL SQL Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Session Title: Using SQL and PL/SQL for Queries and Reporting Presented By: Stephen Frederic Institution: IHL September 16, 2014.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 3 Handling Data in PL/SQL Blocks.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Oracle10g Developer: PL/SQL Programming1 Objectives SQL queries within PL/SQL Host or bind variables The %TYPE attribute Include queries and control structures.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
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.
Oracle11g: PL/SQL Programming Chapter 3 Handling Data in PL/SQL Blocks.
implicit and an explicit cursor
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
RETRIEVE A NO. OF ROWS ¦ Declare a cursor ¦ Open the cursor ¦ Fetch rows of data ¦ Stop fetching rows ¦ Close the cursor.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Section 1 - Introduction to SQL u SQL is an abbreviation for Structured Query Language. u It is generally pronounced “Sequel” u SQL is a unified language.
1 Section 8 - Manipulating Data u The INSERT statement adds rows of data to the database u The UPDATE statement changes columns of existing data u The.
1 Section 3 - Select Statement u The Select statement allows you to... –Display Data –Specify Selection Criteria –Sort Data –Group Data for reporting –Use.
Oracle 11g: SQL Chapter 5 Data Manipulation and Transaction Control.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Joining Tables Steve Perry
1 Section 9 - Views, etc. u Part 1: Views u Part 2:Security Issues u Part 3:Transaction Management u Part 4:Set Operations u Part 5:Triggers and Stored.
A Guide to SQL, Seventh Edition
PL/pgSQL
Interacting with the Oracle Server
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
ATS Application Programming: Java Programming
Chapter 2 - Introduction to C Programming
Interacting with the Oracle Server
Introduction to Oracle9i: SQL
Database Management Systems 2
Error Handling Summary of the next few pages: Error Handling Cursors.
Chapter 2 - Introduction to C Programming
PL/SQL Scripting in Oracle:
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Chapter 2 - Introduction to C Programming
Chapter 8 Advanced SQL.
Chapter 2 - Introduction to C Programming
Presentation transcript:

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 This allows you to both… –pass program variables to SQL statements –receive SQL statement results into program variables

2 Embedded SQL Keywords u There are special SQL keywords that only have meaning with Embedded SQL –INTO –FETCH –DECLARE CURSOR –OPEN CURSOR –CLOSE CURSOR

3 SQL Status Checking u A major difference between Interactive SQL and Embedded SQL is that you must explicitly check for the success or failure of each SQL statement. u Program logic may change based on the return values from SQL statements u Transaction management may change base on the return values from SQL statements

4 Publishers Table u For this presentation, we will use the publishers table from the bookbiz.db database u PUBLISHERS: pub_idvarchar(4)not null pub_namevarchar(40)not null addressvarchar(40) cityvarchar(20) statechar(2)

5 Publishers Table Data u Pub_idPub_nameAddressCity State 0736New Age Books1 1st St.Boston MA 0877Binnet & Hardley2 2nd St.Houston TX 1389Algodata Systems3 3rd St.Berkeley CA

6 Interactive SQL Example u SELECT pub_id, pub_name, state FROM publishers WHERE pub_name = 'New Age Books'; u Returns: 0736 New Age Books MA

7 Using PowerBuilder u For the rest of this presentation we will be using PowerBuilder scripting to illustrate the embedded SQL examples u Other languages may vary in how you specify variable name within a SQL statement u I will be teaching you a few Powerbuilder scripting statements in this presentation

8 The INTO clause u In embedded SQL we use an INTO clause in the SELECT statement to receive information into program variables u SELECT select_list INTO variable_list FROM table_list [ Rest of Statement ];

9 Embedded SQL Example u SELECT pub_id, pub_name, state INTO :ls_pub_id, :ls_pub_name, :ls_state FROM publishers WHERE pub_name = 'New Age Books'; Messagebox("Pub_id for New Age Books", ls_pub_id) u In PowerBuilder, variable names that appear within SQL statements are preceded with a colon ( : )

10 Exercise u Write the code to display the average price of books in a Messagebox window.

11 Discussion u Integer li_price SELECT AVG(price) INTO :li_price FROM titles Messagebox('Average Price', li_price)

12 Exercise u Display in a Messagebox the publisher name for the book "Life Without Fear" (Note: Do not use any join operations or subqueries! )

13 Discussion u String ls_pubname, ls_pub_id SELECT pub_id INTO :ls_pub_id FROM titles WHERE title = 'Life Without Fear'; SELECT pub_name into :ls_pub_name FROM publishers WHERE pub_id = :ls_pub_id Messagebox('Publisher', ls_pub_name)

14 Multiple Return Rows u Preceding SELECT statement examples returned only one row u What do you think will happen if an embedded SELECT returns more than one row?

15 Interactive vs. Embedded u Interactive: –SELECT pub_id, pub_name, state FROM publishers WHERE state LIKE '_A'; –Returns two rows u Embedded: –SELECT pub_id, pub_name, state INTO :ls_pub_id, :ls_pub_name, :ls_state FROM publishers WHERE state LIKE '_A'; –Error Condition!

16 Why? u You've only provided one set of variables for two rows of information –i.e. you can't stuff two pub_names (from the two rows returned) into :ls_pub_name

17 Buffering Returned Data u If there is any possibility that a SELECT statement will return more than one row you must provide a buffer to hold the values u DECLARE CURSOR creates this buffer u This buffer will be read later (one row at a time) using the FETCH statement

18 DECLARE CURSOR Syntax u DECLARE CURSOR FOR ; u Example: –DECLARE pub_cursor CURSOR FOR SELECT pub_id, pub_name, state FROM publishers WHERE state LIKE '_A';

19 Open the Cursor u The DECLARE CURSOR stores the associated SELECT statement, but does not execute it. u The OPEN statement actually executes the stored SELECT statement u Example: –OPEN pub_cursor;

20 Getting the Buffered Data u The OPEN cursor statement retrieves the rows into the buffer u How do we get this information into the program variables?

21 FETCH INTO Statement u To read the buffer one row at a time and get the data into program variables, use the FETCH INTO statement u Syntax: FETCH INTO u Example: FETCH pub_cursor INTO :ls_pub_id, :ls_pub_name, :ls_state;

22 Matching Variables & Columns u The variables declared in the FETCH INTO statement... –must be equal to the number of columns in the SELECT statement saved with the cursor –must be of the same datatype (or convert to the variable datatype)

23 Program Loops u In order to get all the rows in the buffer you must execute the FETCH statement each time you want to get the next row u Place the FETCH in a program loop and exit the loop when there are now more rows to read in the buffer

24 Example u DO FETCH pub_cursor INTO :ls_pub_id, :ls_pub_name, ls_state; If sqlca.sqlcode = 100 then EXIT end if LOOP WHILE TRUE

25 SQLcode u The sqlca.sqlcode variable you saw in the preceding statement is a PowerBuilder specific variable name that stores the return value from an executed SQL statement u Notice that variables within the programming language, (i.e. not in the SQL statement proper), are not preceded with the colon

26 Status Checking u All embedded SQL statements should have there status checked by interrogated the return code (e.g. sqlca.sqlcode) u Return codes and their meaning... –0 means success for all statements including the INSERT, UPDATE & DELETE when no rows are affected –100 means no rows found for the SELECT and means at end of buffer for the FETCH –-1 (minus one) means database error

27 Example u FETCH pub_cursor INTO :ls_pub_id, :ls_pub_name, ls_state; CHOOSE CASE sqlca.sqlcode CASE 0 COMMIT: CASE 100 COMMIT; EXIT CASE -1 ROLLBACK; Messagebox("Database Error", "Process Halted") HALT END CHOOSE

28 COMMIT and ROLLBACK u Remember… –COMMIT saves the updates to the database since the last COMMIT –ROLLBACK un-does the updates to the database since the last COMMIT

29 Close the cursor u To clear the buffer to a close the cursor u Syntax: CLOSE u Example: CLOSE pub_cursor;

30 Example - Embedded INSERT u String ls_test_name ls_test_name = 'Perry Publishing' u INSERT INTO publishers (pub_id, pub_name) VALUES ('9988', :ls_test_name); u When using a constant do not use a colon

31 Example - Embedded UPDATE u string ls_state ls_state = 'CA' u UPDATE publishers SET city = 'Oakland', state = :ls_state WHERE pub_name = :ls_test_name;

32 PowerBuilder Scripting u The following are some PowerBuilder scripting statements that may help you completed the assignment.

33 Declaring a Variable u String –For character based data –example: String ls_last_name u Int –for whole numbers less than –example: Int li_count

34 Displaying Information u MessageBox(, ) –example: String ls_msg ls_msg = 'Something is wrong' MessageBox("Error Found", ls_msg)

35 DO Loop u Executes the script inside the Loop repetitively u Example: Do li_count = li_count + 1 Loop While True u This will add 1 to li_count continually

36 Leaving a Loop u EXIT –Leaves the current loop (e.g DO-LOOP) and continues with the next line of code after the loop –example: DO li_count = li_count + 1 if li_count > 4 then EXIT end if LOOP WHILE TRUE Messagebox("Info","Completed")

37 Stopping Execution u RETURN leaves the currently running script u HALT terminates the entire application

38 Decision Logic u If-Then-Else –example:If li_count > 1 then li_count = 0 else li_count = 1 end if u Choose Case –example:Choose Case li_count Case > 1 li_count = 0 Case Else li_count = 1 End Choose

39 End Section 10 - Embedded SQL u Embedded SQL Assignment is Optional. u Due: Whenever ( me the code) u There are no points added to your grade for this assignment u Use any programming language that allow embedded SQL… That means Not Visual Basic!