# Oracle PL/SQL by Example- P2

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
124
lượt xem
33

## Oracle PL/SQL by Example- P2

Mô tả tài liệu

Tham khảo tài liệu 'oracle pl/sql by example- p2', công nghệ thông tin, cơ sở dữ liệu phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:

Bình luận(0)

Lưu

## Nội dung Text: Oracle PL/SQL by Example- P2

1. LAB 2.1 22 LAB 2.1 PL/SQL Programming Fundamentals LAB OBJECTIVES After completing this lab, you will be able to . Make use of PL/SQL language components . Make use of PL/SQL variables . Handle PL/SQL reserved words . Make use of identifiers in PL/SQL . Make use of anchored datatypes . Declare and initialize variables . Understand the scope of a block, nested blocks, and labels Most languages have only two sets of characters: numbers and letters. Some languages, such as Hebrew and Tibetan, have specific characters for vowels that are not placed inline with conso- nants. Other languages, such as Japanese, have three character types: one for words originally taken from the Chinese language, another set for native Japanese words, and a third for other foreign words. To speak any foreign language, you have to begin by learning these character types. Then you learn how to make words from these character types. Finally, you learn the parts of speech, and you can begin talking. You can think of PL/SQL as being a more-complex language, because it has many character types and many types of words or lexical units that are made from these character types. As soon as you learn these, you can begin learning the struc- ture of the PL/SQL language. CHARACTER TYPES The PL/SQL engine accepts four types of characters: letters, digits, symbols (*, +, –, =, and so on), and white space. When elements from one or more of these character types are joined, they create a lexical unit (these lexical units can be a combination of character types). The lexical units are the words of the PL/SQL language. First you need to learn the PL/SQL vocabulary, and then you will move on to the syntax, or grammar. Soon you can start talking in PL/SQL. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
3. LAB 2.1 Lab 2.1 Exercises 24 B) What are the PL/SQL equivalents of a verb and a noun in English? Do you speak PL/SQL? ANSWER: A noun is similar to the lexical unit called an identifier. A verb is similar to the lexical unit called a delimiter. Delimiters can simply be quotation marks, but others perform a function such as multiplication (*). You do “speak PL/SQL” to the Oracle server. 2.1.2 Make Use of PL/SQL Variables Variables may be used to hold a temporary value. The syntax is as follows: Syntax : variable-name data type [optional default assignment] Variables may also be called identifiers. You need to be familiar with some restrictions when naming vari- ables: Variables must begin with a letter and may be up to 30 characters long. Consider the following example, which contains a list of valid identifiers: FOR EXAMPLE v_student_id v_last_name V_LAST_NAME apt_# Note that the identifiers v_last_name and V_LAST_NAME are considered identical because PL/SQL is not case-sensitive. Next, consider an example of illegal identifiers: FOR EXAMPLE X+Y 1st_year student ID Identifier X+Y is illegal because it contains a + sign. This sign is reserved by PL/SQL to denote an addi- tion operation; it is called a mathematical symbol. Identifier 1st_year is illegal because it starts with a number. Finally, identifier student ID is illegal because it contains a space. Next, consider another example: FOR EXAMPLE SET SERVEROUTPUT ON; DECLARE first&last_names VARCHAR2(30); BEGIN first&last_names := 'TEST NAME'; DBMS_OUTPUT.PUT_LINE(first&last_names); END; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
4. Lab 2.1 Exercises LAB 2.1 25 In this example, you declare a variable called first&last_names. Next, you assign a value to this variable and display the value on the screen. When run, the example produces the following output: Enter value for last_names: Elena old 2: first&last_names VARCHAR2(30); new 2: firstElena VARCHAR2(30); Enter value for last_names: Elena old 4: first&last_names := 'TEST NAME'; new 4: firstElena := 'TEST NAME'; Enter value for last_names: Elena old 5: DBMS_OUTPUT.PUT_LINE(first&last_names); new 5: DBMS_OUTPUT.PUT_LINE(firstElena); TEST NAME PL/SQL procedure successfully completed. Consider the output produced. Because an ampersand (&) is present in the name of the variable first&last_names, a portion of the variable is considered to be a substitution variable (you learned about substitution variables in Chapter 1). In other words, the PL/SQL compiler treats the portion of the variable name after the ampersand (last_names) as a substitution variable. As a result, you are prompted to enter the value for the last_names variable every time the compiler encounters it. It is important to realize that although this example does not produce any syntax errors, the variable first&last_names is still an invalid identifier, because the ampersand character is reserved for substitution variables. To avoid this problem, change the name of the variable from first&last_ names to first_and_last_names. Therefore, you should use an ampersand in the name of a variable only when you use it as a substitution variable in your program. It is also important to consider what type of program you are developing and that is running your PL/SQL statements. This would be true if the program (or PL/SQL block) were executed by SQL*Plus. Later, when you write stored code, you would not use the ampersand, but you would use parameters. BY THE WAY If you are using Oracle SQL Developer, you need to click the leftmost button, Enable DBMS Output, before running this script. FOR EXAMPLE -- ch02_1a.sql SET SERVEROUTPUT ON DECLARE v_name VARCHAR2(30); v_dob DATE; v_us_citizen BOOLEAN; BEGIN DBMS_OUTPUT.PUT_LINE(v_name||'born on'||v_dob); END; A) If you ran this example in a SQL*Plus or Oracle SQL Developer, what would be the result? ANSWER: Assuming that SET SERVEROUTPUT ON had been issued, you would get only born on. The reason is that the variables v_name and v_dob have no values. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
5. LAB 2.1 Lab 2.1 Exercises 26 B) Run the example and see what happens. Explain what is happening as the focus moves from one line to the next. ANSWER: Three variables are declared. When each one is declared, its initial value is null. v_name is set as a VARCHAR2 with a length of 30, v_dob is set as a character type date, and v_us_citizen is set to BOOLEAN. When the executable section begins, the variables have no values. Therefore, when DBMS_OUTPUT is told to print their values, it prints nothing. You can see this if you replace the variables as follows: Instead of v_name, use COALESCE(v_name, 'No Name'), and instead of v_dob, use COALESCE(v_dob, '01-Jan-1999'). The COALESCE function compares each expression to NULL from the list of expressions and returns the value of the first non-null expression. In this case, it compares the v_name variable and ‘No Name’ string to NULL and returns the value of ‘No Name’. This is because the v_name variable has not been initialized and as such is NULL. The COALESCE function is covered in Chapter 5,“Conditional Control: CASE Statements.” Then run the same block, and you get the following: No Name born on 01-Jan-1999 To make use of a variable, you must declare it in the declaration section of the PL/SQL block. You have to give it a name and state its datatype. You also have the option to give your variable an initial value. Note that if you do not assign a variable an initial value, it is NULL. It is also possible to constrain the declaration to “not null,” in which case you must assign an initial value. Variables must first be declared, and then they can be referenced. PL/SQL does not allow forward refer- ences. You can set the variable to be a constant, which means that it cannot change. 2.1.3 Handle PL/SQL Reserved Words Reserved words are ones that PL/SQL saves for its own use (such as BEGIN, END, and SELECT). You cannot use reserved words for names of variables, literals, or user-defined exceptions. FOR EXAMPLE SET SERVEROUTPUT ON; DECLARE exception VARCHAR2(15); BEGIN exception := 'This is a test'; DBMS_OUTPUT.PUT_LINE(exception); END; A) What would happen if you ran this PL/SQL block? Would you receive an error message? If so, what would it say? ANSWER: In this example, you declare a variable called exception. Next, you initialize this variable and display its value on the screen. This example illustrates an invalid use of reserved words. To the PL/SQL compiler,“exception” is a reserved word that denotes the beginning of the exception-handling section. As a result, it cannot be used to name a variable. Consider the huge error message that this tiny example produces: exception VARCHAR2(15); * ERROR at line 2: Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
6. Lab 2.1 Exercises LAB 2.1 27 ORA-06550: line 2, column 4: PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin function package pragma procedure subtype type use cursor form current The symbol "begin was inserted before "EXCEPTION" to continue. ORA-06550: line 4, column 4: PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin declare exit for goto if loop mod null pragma raise return select update while
7. LAB 2.1 Lab 2.1 Exercises 28 In this example, you declare and initialize three variables. The values that you assign to them are literals. The first two values, 'string literal' and '12.345', are string literals because they are enclosed in single quotes. The third value, 12.345, is a numeric literal. When run, the example produces the following output: v_var1: string literal v_var2: 12.345 v_var3: 12.345 PL/SQL procedure successfully completed. Consider another example that uses numeric literals: FOR EXAMPLE SET SERVEROUTPUT ON; DECLARE v_var1 NUMBER(2) := 123; v_var2 NUMBER(3) := 123; v_var3 NUMBER(5,3) := 123456.123; BEGIN DBMS_OUTPUT.PUT_LINE('v_var1: '||v_var1); DBMS_OUTPUT.PUT_LINE('v_var2: '||v_var2); DBMS_OUTPUT.PUT_LINE('v_var3: '||v_var3); END; A) What would happen if you ran this PL/SQL block? ANSWER: In this example, you declare and initialize three numeric variables. The first declaration and initialization (v_var1 NUMBER(2) := 123) causes an error because the value 123 exceeds the specified precision. The second variable declaration and initialization (v_var2 NUMBER(3) := 123) does not cause any errors because the value 123 corresponds to the specified precision. The last declaration and initialization (v_var3 NUMBER(5,3) := 123456.123) causes an error because the value 123456.123 exceeds the specified preci- sion. As a result, this example produces the following output: ORA-06512: at line 2 ORA-06502: PL/SQL: numeric or value error: number precision too large ORA-06512: at line 2 2.1.5 Make Use of Anchored Datatypes The datatype that you assign to a variable can be based on a database object. This is called an anchored declaration because the variable’s datatype is dependent on that of the underlying object. It is wise to make use of anchored datatypes when possible so that you do not have to update your PL/SQL when the datatypes of base objects change. The syntax is as follows: Syntax: variable_name type-attribute%TYPE The type is a direct reference to a database column. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
19. LAB 3.1 40 LAB 3.1 Making Use of DML in PL/SQL LAB OBJECTIVES After completing this lab, you will be able to . Use the SELECT INTO syntax for variable initialization . Use DML in a PL/SQL block . Make use of a sequence in a PL/SQL block VARIABLE INITIALIZATION WITH SELECT INTO PL/SQL has two main methods of giving value to variables in a PL/SQL block. The first one, which you learned about in Chapter 1, “PL/SQL Concepts,” is initialization with the := syntax. In this lab you will learn how to initialize a variable with a select statement by using the SELECT INTO syntax. A variable that has been declared in the declaration section of the PL/SQL block can later be given a value with a select statement. The syntax is as follows: SELECT item_name INTO variable_name FROM table_name; It is important to note that any single row function can be performed on the item to give the variable a calculated value. FOR EXAMPLE -- ch03_1a.sql SET SERVEROUTPUT ON DECLARE v_average_cost VARCHAR2(10); BEGIN SELECT TO_CHAR(AVG(cost), '$9,999.99') INTO v_average_cost FROM course; DBMS_OUTPUT.PUT_LINE('The average cost of a '|| 'course in the CTA program is '|| v_average_cost); END; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 20. Lab 3.1 Exercises LAB 3.1 41 In this example, a variable is given the value of the average cost of a course in the course table. First, the variable must be declared in the declaration section of the PL/SQL block. In this example, the variable is given the datatype of VARCHAR2(10) because of the functions used on the data. The same select statement that would produce this outcome in SQL*Plus is as follows: SELECT TO_CHAR(AVG(cost), '$9,999.99') FROM course; The TO_CHAR function is used to format the cost; in doing this, the number datatype is converted to a character datatype. As soon as the variable has a value, it can be displayed to the screen in SQL*Plus using the PUT_LINE procedure of the DBMS_OUTPUT package. ▼ LAB 3.1 EXERCISES This section provides exercises and suggested answers, with discussion related to how those answers resulted. The most important thing to realize is whether your answer works. You should figure out the implications of the answers and what the effects are of any different answers you may come up with. 3.1.1 Use the Select INTO Syntax for Variable Initialization A) Execute the script ch03_1a.sql. What is displayed on the SQL*Plus screen? Explain the results. ANSWER: You see the following result: The average cost of a course in the CTA program is \$1,198.33 PL/SQL procedure successfully completed. In the declaration section of the PL/SQL block, the variable v_average_cost is declared as a VARCHAR2. In the executable section of the block, this variable is given the value of the average cost from the course table by means of the SELECT INTO syntax. The SQL function TO_CHAR is issued to format the number. The DBMS_OUTPUT is then used to show the result to the screen. B) Take the same PL/SQL block, and place the line with the DBMS_OUTPUT before the SELECT INTO statement. What is displayed on the SQL*Plus screen? Explain what the value of the variable is at each point in the PL/SQL block. ANSWER: You see the following result: The average cost of a course in the CTA program is PL/SQL procedure successfully completed. The variable v_average_cost is set to NULL when it is first declared. Because the DBMS_OUTPUT is placed before the variable is given a value, the output for the variable is NULL. After the SELECT INTO, the variable is given the same value as in the original block described in question A, but it is not displayed because there is no other DBMS_OUTPUT line in the PL/SQL block. Data Definition Language (DDL) is not valid in a simple PL/SQL block. (More-advanced techniques such as procedures in the DBMS_SQL package enable you to make use of DDL.) However, DML is easily achieved either by use of variables or by simply putting a DML statement into a PL/SQL block. Here is an example of a PL/SQL block that UPDATEs an existing entry in the zip code table: Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.