a guide to sql, sixth edition 1 chapter 8 embedded sql

44
1 A Guide to SQL, Sixth Edition Chapter 8 Embedded SQL

Upload: gladys-lewis

Post on 18-Dec-2015

238 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

1

A Guide to SQL, Sixth Edition

Chapter 8Embedded SQL

Page 2: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

2

Objectives

Embed SQL commands in PL/SQL programs

Retrieve single rows using embedded SQL

Update a table using embedded INSERT, UPDATE, and DELETE commands

Use cursors to retrieve multiple rows in embedded SQL

Page 3: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

3

Objectives

Update a database using cursors

Manage errors in programs containing embedded SQL commands

Use SQL in a language that does not support embedded SQL commands

Page 4: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

4

Introduction

SQL is a non-procedural language

Non-procedural language: many tasks can be accomplished using a single, relatively simple command

Procedural language: computer must be given the step-by-step process for accomplishing tasks

Page 5: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

5

Introduction

PL/SQL procedural language developed by Oracle an extension of SQL

This chapter uses PL/SQL to illustrate how to embed SQL commands in another language

To embed SQL commands means to include SQL commands directly within programs written in another language

Page 6: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

6

Using Prompt Variables

There are many sources of input for SQL commands

In this text, input comes from prompt variables

Prompt variables: variables for which the user is prompted to enter a value

To designate a prompt variable, precede the name with an ampersand (&)

Page 7: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

7

Using Prompt Variables

Problem:List the last name of the sales rep whose

number is contained in the prompt variable I_REP_NUM.

Solution:SQL> SELECT LAST_NAME2 FROM REP3 WHERE REP_NUM = '&I_REP_NUM';

Page 8: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

8

PL/SQL Programs

SQL commands can be embedded in PL/SQL programs

The programs can be created and saved as script files

To run the programs, run the script files

Page 9: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

9

Retrieving a Single Row and Column

Problem:Write a PL/SQL program to obtain the last

name of the sales rep whose number is contained in the prompt variable I_REP_NUM, place it in the variable I_LAST_NAME, and then display the contents of I_LAST_NAME.

Page 10: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

10

Retrieving a Single Row and Column

To place the results of a command in a variable, use the INTO clause

To see the contents of the line (the output), use:

SET SERVEROUTPUT ON

Page 11: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

11

Retrieving a Single Row and Column

Solution:SET SERVEROUTPUT ONDECLAREI_REP_NUM CHAR(2);I_LAST_NAME CHAR(15);BEGINSELECT LAST_NAMEINTO I_LAST_NAMEFROM REPWHERE REP_NUM = '&I_REP_NUM';DBMS_OUTPUT.PUT_LINE(I_LAST_NAME);END;/

Page 12: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

12

Using the %Type Attribute

%TYPE attribute: ensures that a variable has the same type as a particular column

To assign the variable I_REP_NUM the same type as the REP_NUM column in the REP table, use the following: 

I_REP_NUM REP.REP_NUM%TYPE

Page 13: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

13

Retrieving a Single Row from a Join

An embedded SQL command can be used to join tables

Problem:Obtain the name of the customer whose

customer number is stored in the prompt variable I_CUSTOMER_NUM, and the last and first names of the sales rep who represents this customer.

Page 14: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

14

Retrieving a Single Row from a Join

SET SERVEROUTPUT ONDECLAREI_LAST_NAME REP.LAST_NAME%TYPE;I_FIRST_NAME REP.FIRST_NAME%TYPE;I_CUSTOMER_NUM CUSTOMER.CUSTOMER_NUM%TYPE;I_CUSTOMER_NAME CUSTOMER.CUSTOMER_NAME%TYPE;BEGINSELECT LAST_NAME, FIRST_NAME, CUSTOMER_NAMEINTO I_LAST_NAME, I_FIRST_NAME, I_CUSTOMER_NAMEFROM REP, CUSTOMERWHERE REP.REP_NUM = CUSTOMER.REP_NUMAND CUSTOMER_NUM = '&I_CUSTOMER_NUM';DBMS_OUTPUT.PUT_LINE(I_CUSTOMER_NAME);DBMS_OUTPUT.PUT_LINE(I_LAST_NAME);DBMS_OUTPUT.PUT_LINE(I_FIRST_NAME)END;/

Page 15: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

15

Inserting a Row into a Table

To update databases from within PL/SQL programs, appropriate SQL commands are usedSQL INSERT: add a row to a table in the database Problem:Add a row to the REP table. Use prompt

variables to obtain values for the fields.

Page 16: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

16

Inserting a Row into a Table

The procedural code part of the solution program is:

BEGININSERT INTO REP (REP_NUM, LAST_NAME, FIRST_NAME, STREET, CITY, STATE, ZIP, COMMISSION, RATE)VALUES('&I_REP_NUM', '&I_LAST_NAME', '&I_FIRST_NAME', '&I_STREET', '&I_CITY', '&I_STATE', '&I_ZIP',&I_COMMISSION, &I_RATE);END;

Page 17: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

17

Changing a Single Row in a Table

SQL commands can also be used to update the rows in a database

Problem:Change the last name of the sales rep

whose number is stored in I_REP_NUM to the value currently stored in I_LAST_NAME.

Page 18: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

18

Changing a Single Row in a Table

Solution:SET SERVEROUTPUT ONDECLAREI_REP_NUM REP.REP_NUM%TYPE;I_LAST_NAME REP.LAST_NAME%TYPE; BEGINUPDATE REPSET LAST_NAME = '&I_LAST_NAME‘WHERE REP_NUM = '&I_REP_NUM';END;/

Page 19: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

19

Deleting Rows from a Table

SQL commands can be used to delete rows

Problem:Delete the sales rep whose number

currently is stored in I_REP_NUM from the REP table.

Page 20: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

20

Deleting Rows from a Table

Solution:SET SERVEROUTPUT ON DECLAREI_REP_NUM REP.REP_NUM%TYPE; BEGINDELETEFROM REPWHERE REP_NUM = '&I_REP_NUM'; END;/

Page 21: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

21

Deleting Rows from Multiple Tables

SQL commands can be used to delete more than one row from a tableProblem:Delete the order whose number is stored in

I_ORDER_NUM from the ORDERS table, and then delete each order line for the order whose order number is currently stored in the variable from the ORDER_LINE table.

Page 22: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

22

Deleting Rows from Multiple Tables

Solution:DECLAREI_ORDER_NUM ORDERS.ORDER_NUM%TYPE;W_ORDER_NUM CHAR(5);BEGINI_ORDER_NUM := &W_ORDER_NUM;DELETEFROM ORDER_LINEWHERE ORDER_NUM = I_ORDER_NUM;DELETEFROM ORDERSWHERE ORDER_NUM = I_ORDER_NUM;END;/

Page 23: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

23

Multiple-Row Select

A SELECT command that retrieves multiple rows poses a problem since PL/SQL can process only one record at a time

This problem can be solved by using a cursor

Page 24: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

24

Using Cursors

Cursor: a pointer to a row in the collection of rows retrieved by a SQL command

The cursor advances one row at a time to provide sequential, one-record-at-a-time access to the retrieved rows

By using a cursor, PL/SQL can process the set of retrieved rows as though they were records in a sequential file

Page 25: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

25

Using Cursors

Using a cursor in the procedural portion of the program involves three commands: OPEN: opens the cursor and causes the query to

be executed FETCH: advances the cursor to the next row in the

set of rows retrieved by the query and places the contents of the row in the indicated variables

CLOSE: closes a cursor and deactivates it

Page 26: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

26

Opening a Cursor

Prior to opening the cursor, there are no rows available to be fetched

The OPEN command to open the CUSTGROUP cursor is:

OPEN CUSTGROUP;

Page 27: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

27

Fetching Rows from a Cursor

FETCH: fetch (get) the next row from a cursor

The FETCH command is written as follows:

FETCH CUSTGROUP INTO I_CUSTOMER_NUM, I_CUSTOMER_NAME;

Page 28: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

28

Closing a Cursor

The CLOSE command is written as follows:

CLOSE CUSTGROUP;

Page 29: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

29

Advantages of Cursors

The three main advantages of using cursors: The coding in the program is greatly simplified In a program using embedded SQL, a special

component of the DBMS called the optimizer determines the best way to access the data

If the database structure changes in such a way that the necessary information is still obtainable using a different query, the only change required in the program is the cursor definition

Page 30: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

30

Updating Cursors

Data can be updated through a cursor by using the FOR UPDATE OF clause

A WHERE clause can be used to restrict the scope of the update

Page 31: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

31

Error Handling

Programs must be able to handle exceptional conditions that can arise when accessing the database

For example, a user might enter a value that would cause an error to occur

Errors can be handled by using the EXCEPTION command

Page 32: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

32

Using SQL in Microsoft Access Programs

In Microsoft Access, programs are written in Visual Basic

Visual Basic does not allow the inclusion of SQL commands directly in the code

If the SQL command is stored in a string variable, the DoCmd.RunSQL command can be used to run the command

Page 33: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

33

Using SQL in Microsoft Access Programs

The procedure in which you place the SQL command can include arguments

Arguments are values that provide information to the procedure

Example: In a procedure to delete a sales rep, the

argument would be the sales rep number

Page 34: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

34

Deleting Rows

To delete the sales rep whose number is 20, the command is: DELETE FROM REP WHERE REP_NUM = '20';

Usually, the specific sales rep number to delete is not known in advanceIt can be passed as an argument to the procedure containing the DELETE commandA procedure is entered in the Microsoft Visual Basic window

Page 35: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

35

Deleting Rows

Microsoft Visual Basic window

Page 36: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

36

Running the Code

Normally, you run a function by:Calling it from another procedureAssociating it with some event

Functions can also be run directly by using the Immediate window

Page 37: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

37

Running the Code

The Immediate window

Page 38: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

38

Running the Code

To run a function procedure in the Immediate window: Type:

A question mark The name of the procedure A set of parentheses

Place the values for any arguments in the parentheses

After typing the command, press the Enter key

Page 39: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

39

Updating Rows

A procedure can update a table by using an UPDATE command

Such a procedure would be similar to the one used to delete a sales rep

Page 40: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

40

Inserting Rows

The process for inserting rows is similar

The appropriate INSERT command is created in the strSQL variable

There will be multiple arguments in the procedure—one for each value to be inserted

Page 41: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

41

Finding Rows

A SELECT command that returns several rows poses serious problems for record-at-a-time languages like PL/SQL and Visual Basic

For such SELECT commands, the results of a query are handled in the same way as a loop is used to process through the records in a table

Page 42: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

42

SummaryTo embed a SQL command in a PL/SQL program, type it in the procedural codeVariables in PL/SQL programs are declared after the word DECLARETo assign variables the same type as a column, use the %TYPE attributeYou can request user input in SQL commands by using prompt variablesIf a SELECT command is to retrieve more than one row, define a cursor to select one row at a time

Page 43: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

43

SummaryData in the tables on which a cursor is based can be updated with FOR UPDATE OFTo see whether an error has occurred, use the EXCEPTION commandTo use SQL commands in Access, create the command in a string variableTo run the command stored in the string variable, use DoCmd.RunSQLTo process a collection of rows retrieved by a SELECT in Access, use a recordset

Page 44: A Guide to SQL, Sixth Edition 1 Chapter 8 Embedded SQL

44

SQL Project Eight Completed

Good Luck

H. Zamanzadeh