1. Trang chủ
  2. » Công Nghệ Thông Tin

specifying variables at runtime

28 231 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Specifying variables at runtime
Trường học University of Information Technology
Chuyên ngành Oracle SQL and PL/SQL
Thể loại bài giảng
Thành phố Ho Chi Minh City
Định dạng
Số trang 28
Dung lượng 181,64 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Interactive Reports To create interactive reports, you can embed substitution variables in a command file or in single SQL commands.. Introduction to Oracle: SQL and PL/SQL Using Procedu

Trang 1

Specifying Variables at Runtime

7

Trang 2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć2

35 minutes Lecture

25 minutes Practice

60 minutes Total

Class Management Note:

Files required for this lesson are:

Demonstration: l7varno.sql, l7varyes.sql, l7expr.sql, l7dbl.sql, l7dlb2.sql, l7prompt.sql, l7param.sql

Practice: None

Trang 3

You can create a command file containing a WHERE clause to restrict the rows displayed To change the condition each time the command file is run, you use substitution variables Substitution variables can replace values in the WHERE clause, a text string, and even a column or a table name.

At the end of this lesson, you should be able to

D Create a SELECT statement that prompts the user to enter a value at runtime

D Use the SQL*Plus ACCEPT command to define a variable

D Define a variable that can be automatically picked up by the SELECT statement

at runtime

Trang 4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć4

Class Management Note:

1 Execute the script At the prompt, enter: sales

Output is restricted to rows satisfying that request

2 Execute the script again This time, at the prompt enter: PRESIDENT

Question: How does the value become case-insensitive?

Answer: The UPPER function and the LIKE operator are in the WHEREclause instead of the = operator

Trang 5

The reports produced so far have not been interactive in any way In a finished

application, the user would trigger the report, and the report would run withoutfurther prompting The range of data reported would be predetermined by the fixedWHERE clause in the SQL*Plus script file However, SQL*Plus enables you tocreate reports that prompt the user to supply their own values to restrict the range ofdata returned

Interactive Reports

To create interactive reports, you can embed substitution variables in a command file

or in single SQL commands A variable can be thought of as a container in whichvalues are temporarily stored

Trang 6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć6

Trang 7

Substitution Variables

In SQL*Plus, you can use single ampersand substitution variable to temporarily storevalues

You can predefine variables in SQL*Plus by using the ACCEPT or DEFINE

commands ACCEPT reads a line of user input and stores it in a variable DEFINEcreates and assigns a value to a variable

Examples of Restricted Ranges of Data

D Report figures for the current quarter or specified date range only

D Report on data relevant to the user requesting the report only

D Display personnel within a given department only

Other Interactive Effects

Interactive effects are not restricted to direct user interaction with the WHEREclause The same principles can be used to achieve other goals, for example:

D Dynamically altering headers and footers

D Obtaining input parameters from a file rather than from a person

D Passing values from one SQL statement to another

SQL*Plus does not support validation checks on user input Make sure that theprompts you write for the user are simple and unambiguous

Trang 8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć8

Trang 9

Single Ampersand Substitution Variables

When running a report, users often want to restrict the data returned dynamically.SQL*Plus provides this flexibility by means of user variables Use an ampersand (&)

to identify each variable in your SQL statement You do not need to define the value

of each variable

Notation Description

&user_variable Indicates a variable in a SQL statement; if the variable does

not exist, SQL*Plus prompts the user for a value

SQL*Plus discards a new variable once it is used

3 WHERE dept_id = &department_number;

Enter value for department_number: 31

ID LAST_NAME SALARY

-

3 Nagayama 1400

11 Magee 1400

With the single ampersand, the user is prompted every time the command is executed

SET VERIFY Command

To confirm the changes in the SQL statement, use the SQL*Plus SET VERIFYcommand Setting SET VERIFY to ON forces SQL*Plus to display the text of acommand before and after it replaces substitution variables with values

Trang 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć10

Trang 11

Single Ampersand Substitution Variables continued

Specifying Character and Date Values with Substitution Variables

Remember that in a WHERE clause, date and character values must be enclosedwithin single quotation marks The same rule applies to the substitution variables

To avoid entering the quotation marks at run time, enclose the variable in singlequotation marks within the SQL statement itself

3 WHERE title = ’&job_title’;

Enter value for job_title: Stock Clerk

Trang 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć12

Class Management Note:

DEMO: l7expr.sql

PURPOSE: Show students that you can change the column names andconditions by using substitution variables Run this script twice using thefollowing values:

1 Run the script At the prompt for column name, enter: total

At the prompt for condition, enter: payment_type = ’CASH’

2 Run the script again At the prompt for column name,

enter: date_ordered

At the prompt for condition, enter: total > 300000

Trang 13

Single Ampersand Substitution Variables continued

Specifying Column Names, Expressions, and Text at Runtime

Not only can you use the substitution variables in the WHERE clause of a SQLstatement, but these variables can be used to substitute column names, expressions, ortext

Examples

Display the number and any other column and any condition of orders Try a couple

of variations of column names and conditions to observe the results

SQL> SELECT id, &column_name

2 FROM s_ord

3 WHERE &condition;

Enter value for column_name: total

Enter value for condition: payment_type = ’CASH’

Enter value for column_name: date_ordered

Enter value for condition: total > 300000

ID DATE_ORDE

-

100 31-AUG-92

109 08-SEP-92

Trang 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć14

Trang 15

Defining User Variables

You can predefine user variables before executing a SELECT statement SQL*Plusprovides two commands for defining and setting user variables: DEFINE and

ACCEPT variable [datatype][FORMAT][PROMPT text][HIDE]

where: variable is the name of the variable that stores the value

If it does not exist, SQL*Plus creates it

datatype is either NUMBER, CHAR, or DATE CHAR

has a maximum length limit of 240 bytes.DATE checks against a format model, and thedatatype is CHAR

FOR[MAT] specifies the format model, for example A10 or

Note: Do not prefix the SQL*Plus substitution parameter with the ampersand (&)

when referencing the substitution parameter in the ACCEPT command

Class Management Note:

New features in SQL*Plus 3.2 for the ACCEPT command are FORMAT,

Trang 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć16

Class Management Note:

DEMO: l7prompt.sql

PURPOSE: Demonstrate an ACCEPT statement and a joined SELECTstatement

1 Execute the script At the prompt, enter: sales

2 Notice that the value the user enters at the prompt is case-insensitive because an UPPER function is in the WHERE clause and can search for portions of text because of the LIKE operator

3 Execute the script again At the prompt, enter: Admin

Trang 17

Defining User Variables continued

D Use the ACCEPT command to

D Give a customized prompt when accepting user input Otherwise, you will see

the default “Enter value for variable.”

D Explicitly define a NUMBER or DATE datatype variable

D Hide user input for security reasons

Example

Display the region number and name for a specified department name Create a script

file called l7prompt.sql, and use the ACCEPT command to prompt the user with a

customized message

SET ECHO OFF

ACCEPT p_dname PROMPT ’Provide the department name: ’SELECT d.name, r.id, r.name ”REGION NAME”

FROM s_dept d, s_region r

WHERE d.region_id = r.id

AND UPPER(d.name) LIKE UPPER(’%&p_dname%’)

/

SET ECHO ON

SQL> START l7prompt

Provide the department name: sales

SET ECHO Command

Trang 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć18

Trang 19

Defining User Variables continued

Variables are defined until you either

D Issue the UNDEFINE command on a variable

D Exit SQL*Plus

When you undefine variables, you can verify your changes with the DEFINE

command When you exit SQL*Plus, variables defined during that session are lost

To define those variables for every session, modify your login.sql file so that those

variables are created at startup

Trang 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć20

Class Management Note:

DEMO: l7param.sql

PURPOSE: Demonstrate how to use the parameter in the command line

1 Edit the script see how the substitution variable is positioned in the SELECT statement

2 Run the script to display all the presidents

Enter: START l7param President

3 Change the variable Enter: START l7param ‘Stock Clerk’

Be sure to enclose the two words in single quotation marks

Trang 21

Passing Values into a Script File

A parameter is a value that you can pass to a report by means of the command line.

To create and run a parameterized report, follow these steps:

1. Create a script file to include the SELECT statement

2. In the SELECT statement, use the notation &number for each variable reference.

3. In the command line, specify a value following the filename Use a space toseparate values

Example

Create a script file, l7param.sql, to produce a series of reports by job title Instead of

prompting you for the title, you enter the job title on the command line when youstart the file

SET ECHO OFF

SELECT id, last_name, salary

D A prefix can be used to differentiate column names (no prefix), simple variables

(for example, v_test), and parameterized variables (for example, p_name).

D The position of each parameter value in the command line is significant The firstvalue corresponds to &1, the second parameter to &2, and onward

D Reports can accept a maximum of nine parameters that are named from &1 to &9

D SQL*Plus retains report parameters and their values until you redefine them,undefine them, or terminate your SQL*Plus session

Trang 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć22

Trang 23

Substitution variables are useful for running reports They allow flexibility to replacevalues in a WHERE clause, column names, and expressions You can customizereports by writing script files with

D Single ampersand substitution variables

D The ACCEPT command

D The DEFINE command

D The UNDEFINE command

D Substitution variables in the command line

Trang 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć24

Trang 25

Practice Overview

This practice gives you the opportunity to create files that can be run interactively byusing substitution variables to create runtime selection criteria

Practice Contents

D Creating a query to display values using substitution variables

D Starting a command file containing substitution variables

D Using the ACCEPT command

Class Management Note:

Duration: 25 minutes

Trang 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć26

Practice 7

Determine whether the following statements are true or false

1. A single ampersand substitution variable prompts only once

True / False

2. The ACCEPT command is a SQL command

True / False

The following questions use the S_EMP, S_CUSTOMER, and S_PRODUCT tables

3. Write a script file to display the user name, first and last names concatenatedtogether, and start dates of employees within a specified range Prompt the userfor the two ranges by using the ACCEPT command Use the format MM/DD/YY

Save the script file as p7q3.sql Your result should look like the output below.

Enter the low date range (’MM/DD/YY’): 09/01/91

Enter the high date range (’MM/DD/YY’): 09/01/92

USERID EMPLOYEE START_DAT - - -acatchpo Antoinette Catchpole 09-FEB-92hgiljum Henry Giljum 18-JAN-92mnguyen Mai Nguyen 22-JAN-92adumas Andre Dumas 09-OCT-91emaduro Elena Maduro 07-FEB-92

Trang 27

Practice 7 continued

4. Write a script to search for customer names and numbers The search condition

should allow for case-insensitive name searches Save the script file as p7q4.sql.

Your result should look like the output below

Please enter the customer’s name: sport

Trang 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 7Ć28

If you have time, complete the following exercises

5. Write a report containing the sales representative name, customer name, and eachcustomer’s total sales order Prompt the user for a region number Save the script

as p7q5.sql.

SQL> START p7q5

Please enter a region number: 1

EMPLOYEE CUSTOMER SALES––––––––––– –––––––––––––––––––––––––––– ––––––––––Colin Magee Beisbol Si! $2,722Colin Magee Big John’s Sports Emporium $1,020,935Colin Magee Ojibway Retail $1,539Colin Magee Womansport $603,870

Ngày đăng: 26/10/2013, 23:15