Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
2,67 MB
Nội dung
Learning the Basics of PL/SQL 27 1 TEXT_IO.PUT_LINE(SS_THRESH); When you execute this statement, Procedure Builder will execute the function and dis- play the following results: 72600 Connecting to a Database In addition to creating PL/SQL program units on the client, Procedure Builder can also be used to create and execute program units in a database. To do this, you first need to connect to a database. Use the File, Connect menu option to connect to a database. Once you’ve logged in, you will be able to browse database program units using the Object Navigator. Figure 1.8 shows the program units owned by the user named JEFF . F IGURE 1.6 Creating a New Program Unit. F IGURE 1.7 Entering the code for SS_THRESH . I NPUT O UTPUT 03 7982 ch01 11.8.00 11:22 AM Page 27 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. To create a stored function or other program unit in the database, follow these steps: 1. Click to highlight the Stored Program Units entry under the user’s name. 2. Click the Create Toolbar button. 3. Proceed as you would when creating a local program unit. Except for having to choose the schema, the process for creating a PL/SQL function in the database is the same as for creating one locally. Using SQLPlus Worksheet If you have Enterprise Manager available, consider using SQLPlus Worksheet for the examples in this book. SQLPlus Worksheet is completely compatible with SQL*Plus, and can be used for all the examples in this book. The advantage that SQL*Plus work- sheet has over SQL*Plus is in the interface. Rather than type in large blocks of code one line at a time, you can use a text editor-like interface. After you get the code entered the way that you want it, you can click a toolbar button to execute it. Executing a PL/SQL Block Using SQLPlus Worksheet Figure 1.9 shows the SQLPlus Worksheet. 28 Day 1 F IGURE 1.8 Program units in the JEFF schema. The Create Toolbar button 03 7982 ch01 11.8.00 11:22 AM Page 28 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Learning the Basics of PL/SQL 29 1 As you can see, the SQLPlus Worksheet screen is divided into two halves. The upper half is used for the entry and editing of SQL statements and PL/SQL blocks. The lower half is used to display output. The execute toolbar button, the one with the lightning bolt, is used to execute the statements that you have entered in the upper pane. There are two ways to use SQLPlus Worksheet to execute commands from a file. One way is to use the File, Open menu option to load the contents of a file into the upper pane, and then click the lightning bolt button. The other way is to use the Worksheet, Run Local Script menu option. Summary In this chapter you learned a little about PL/SQL, what it is, and why it is used. You know that PL/SQL is Oracle’s procedural language extension to SQL, and that you can use it to write procedures and functions that execute on the server. This chapter also explains the relationship between PL/SQL, SQL, and SQL*Plus. This should give you a good grasp of how PL/SQL fits into the larger Oracle picture. You wrote your first PL/SQL stored function, which should give you a good feel for the mechanics of programming with PL/SQL. F IGURE 1.9 The SQLPlus Worksheet. The Execute Button The Entry Pane The Output Pane 03 7982 ch01 11.8.00 11:22 AM Page 29 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. SQL*Plus is the tool used throughout this book for PL/SQL code examples. SQLPlus Worksheet and Procedure Builder are two other tools that may also be used to write and execute PL/SQL code. Q&A Q Where does PL/SQL code execution take place? A Usually, execution takes place at the server level. For the examples in this book, that will always be the case. Some Oracle products, such as Developer/2000, also have the capability to execute PL/SQL blocks locally on the client machine. Q Can I write a complete application with PL/SQL? A Generally speaking you cannot, at least not as most people envision an application. For an end-user application, you would still need a tool, such as PowerBuilder or Developer/2000, in order to design screens and generate reports. QI executed some PL/SQL code which used dbms_output.put_line() to print some data, but I didn’t see anything. How come? A You probably forgot to enable the server output option. Use this SQL*Plus command: SET SERVEROUTPUT ON If you forget that, your PL/SQL output goes to oblivion. QI am using Procedure Builder, and I get errors when I try to execute code that contains calls to dbms_output.put_line() . Why? A When you use Procedure Builder to execute code locally, you must use text_io.put_line rather than dbms_output.put_line() . If you are using Procedure Builder, and you have connected to a database, you will be able to exe- cute calls to dbms_output.put_line() ,but you won’t see the results. Workshop Use the following workshop to test your comprehension of this chapter and put what you’ve learned into practice. You’ll find the answers to the quiz and exercises in Appendix A, “Answers.” 30 Day 1 03 7982 ch01 11.8.00 11:22 AM Page 30 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Learning the Basics of PL/SQL 31 1 Quiz 1. What tells SQL*Plus to send your PL/SQL code to the Oracle database for execution? 2. What is the fundamental basis of all PL/SQL code? 3. List an advantage of pushing program logic up to the server level. 4. Name three Oracle products that use PL/SQL. 5. What command tells SQL*Plus to display PL/SQL output? 6. Name at least two options for managing your PL/SQL source code. Exercises 1. If you didn’t encounter any errors when compiling your first function, try putting some in on purpose. Then try out the SHOW ERRORS command. 2. Try each of the three ways mentioned in the chapter for managing your source code. Become familiar with the SQL*Plus EDIT command. Try using the @ com- mand or the START command to execute your PL/SQL code from a text file. 03 7982 ch01 11.8.00 11:22 AM Page 31 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 03 7982 ch01 11.8.00 11:22 AM Page 32 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. D AY 2 W EEK 1 Writing Declarations and Blocks by Jonathan Gennick The block is the fundamental unit of PL/SQL programming. Blocks contain both program code and variable declarations. Understanding the various datatypes available to you when declaring variables is crucial when program- ming in any language, and PL/SQL is no exception. It’s also important to understand PL/SQL’s block structure, its use, and its impact on the scope of variable declarations. Today you are going to learn more about • PL/SQL datatypes • PL/SQL blocks • Scoping rules 04 7982 ch02 11.8.00 11:22 AM Page 33 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Exploring Datatypes PL/SQL provides a number of datatypes for your use, and they can be grouped into sev- eral categories: scalar datatypes, large object datatypes, records, and pointers. This chap- ter focuses on the scalar types, which are listed in Table 2.1. Later in the book, you’ll learn about the other categories. A scalar variable is a variable that is not made up of some combination of other variables. Scalar variables don’t have internal components that you can manipu- late individually. They are often used to build up more complex datatypes such as records and arrays. T ABLE 2.1 PL/SQL Datatypes Datatype Usage VARCHAR2 Variable-length character strings CHAR Fixed-length character strings NUMBER Fixed or floating-point numbers BINARY_INTEGER Integer values PLS_INTEGER New in version 2.3; used for fast integer computations DATE Dates BOOLEAN true / false values NVARCHAR2 Variable-length character strings using the national character set NCHAR Fixed-length character strings using the national character set ROWID Used to store physical rowids (obsolete, use UROWID instead) UROWID Used to store both physical and logical rowids LONG Used to store long character strings (obsolete) LONG RAW Used to store large amounts of binary data (obsolete) RAW Used to store binary data (obsolete) These datatypes can be used for creating simple scalar variables, or they can be com- bined into structures such as records or PL/SQL tables. You will learn more about records and tables during Day 8, “Using SQL.” The LONG , LONG RAW , and RAW datatypes are obsolete. If you’re dealing with large objects, you should use the new large object types instead. Those are covered in Day 14, “Leveraging Large Object Types.” You might notice that some of the datatype names match those used by Oracle for defin- ing database columns. In most cases the definitions are the same for both the database and PL/SQL, but there are a few differences. These differences are noted later in this chapter when each datatype is discussed in detail. 34 Day 2 N EW T ERM 04 7982 ch02 11.8.00 11:22 AM Page 34 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing Declarations and Blocks 35 2 PL/SQL also provides subtypes of some datatypes. A subtype represents a spe- cial case of a datatype, usually representing a narrower range of values than the parent type. For example, POSITIVE is a subtype of BINARY_INTEGER that holds only pos- itive values. In some cases, the subtypes exist only to provide alternative names for com- patibility with the SQL standard or other popular database brands on the market. N EW T ERM Variable Naming Rules Before you go on to learn about each of the datatypes in detail, you should first consid- er some basic rules and conventions for naming variables. Oracle has some simple rules for variable naming. Variable names can be composed of letters, dollar signs, under- scores, and number signs. No other characters can be used. A variable name must start with a letter, after which any combination of the allowed characters can be used. The maximum length for a variable name is 30 characters. Variable names, like those of key- words and other identifiers, are not case-sensitive. In addition to the preceding rules, it is often helpful to follow some sort of naming con- vention for variables and to make their names as descriptive as possible. For example, although empyersal is a legal variable name, your code might be easier to read if you used emp_yearly_salary . Another option, which uses capital letters to highlight each word in order to dispense with the underscores, is EmpYearlySalary . Many program- mers also capitalize language keywords in order to more easily distinguish them from variable, function, and procedure names. The naming rules for variables also apply to function and procedure names. The impor- tance of a consistent naming convention for all identifiers is discussed in more detail in Day 13, “Debugging Your Code and Preventing Errors.” In the next few sections, you’ll learn about each of the PL/SQL datatypes. You’ll learn the type of data that each one holds, what the range of possible values is, and any sub- types that are defined for it. VARCHAR2 The VARCHAR2 datatype is used to hold variable-length character string data. It typically uses 1 byte per character and has a maximum length of 32767 bytes. The Syntax for the VARCHAR2 Datatype variable_name VARCHAR2(size); In this syntax, variable_name is whatever name you want to give to the variable, and size is the maximum length, in bytes, of the string. S YNTAX 04 7982 ch02 11.8.00 11:22 AM Page 35 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Here are some examples: employee_name VARCHAR2(32); employee_comments VARCHAR2(10000); 36 Day 2 Even though PL/SQL allows a maximum of 32767 bytes for a VARCHAR2 vari- able, the Oracle database does not. The Oracle database itself only allows VARCHAR2 columns to be a maximum of 4000 bytes long. You can use longer strings in PL/SQL, but 4000 is the limit (2000 if you are using any release of Oracle7) if you want to store the string in the database. Note Referring to the example declaration of employee_name , here are some sample assign- ment statements showing values that could be assigned to this variable: employee_name := ‘Jenny Gennick’; employee_name := ‘Jonathan Gennick’; VARCHAR2 Subtypes Oracle has two subtypes defined for VARCHAR2 , which are • VARCHAR • STRING These subtypes exist for compatibility with other database brands and also with the SQL standard. Both have the exact same meaning as VARCHAR2 . However, Oracle currently rec- ommends against using the VARCHAR datatype because its definition is expected to change as the SQL standards evolve. CHAR The CHAR datatype is used to hold fixed-length character string data. Unlike VARCHAR2 strings, a CHAR string always contains the maximum number of characters. Strings shorter than the maximum length are padded with spaces. Like VARCHAR2 ,the CHAR datatype typ- ically uses 1 byte per character and has a maximum length of 32767 bytes. The Syntax for the CHAR Datatype variable_name CHAR(size); In this syntax, variable_name is whatever you want to call the variable, and size is the size, in bytes, of the string. Here are some examples: employee_name CHAR(32); employee_comments CHAR(10000); S YNTAX 04 7982 ch02 11.8.00 11:22 AM Page 36 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... my_integer BINARY_INTEGER; A BINARY_INTEGER variable can store any integer value in the range –2,147,483,647 through 2,147,483,647 Tip If you are running PL/SQL version 2.3 or later, you have access to the new PLS_INTEGER datatype, which is optimized for fast calculations For new applications, use PLS_INTEGER instead of BINARY_INTEGER BINARY_INTEGER Subtypes Oracle has defined four subtypes for the BINARY_INTEGER... Jeff Gennick Back in the main block Jeff Gennick The code shown in Listing 2.9 consists of two nested anonymous blocks and one procedure definition The outermost block begins at line 3 and ends on line 31 A nested anonymous block begins on line 14 and ends on line 21 Lines 6 through 9 define the name_print procedure ANALYSIS The variable a_name is declared in the outermost block (see line 4), thus any... datatype is new in release 2.3 of PL/SQL and is used for declaring signed integer variables Like the BINARY_INTEGER datatype, it also stores values in the range –2,147,483,647 through 2,147,483,647 How is it different from a BINARY_INTEGER? The PLS_INTEGER datatype uses the native machine instructions for performing computations Thus, PLS_INTEGER calculations are much faster than BINARY_INTEGER calculations,... BINARY_INTEGER SYNTAX The BINARY_INTEGER datatype is used for declaring signed integer variables Compared to the NUMBER datatype, BINARY_INTEGER variables are stored in binary format, which takes less space Calculations on binary integers can also run slightly faster because the values are already in a binary format The Syntax for the BINARY_INTEGER Datatype variable_name BINARY_INTEGER; In this syntax, variable_name... DBMS_OUTPUT.PUT_LINE(a_name); DBMS_OUTPUT.PUT_LINE(b_name); name_print; END; Writing Declarations and Blocks 22: 23: DBMS_OUTPUT.PUT_LINE(‘Back in the main block’); 24: 25: But we cannot compile the following line because b_name 26: is not defined in this block 27: DBMS_OUTPUT.PUT_LINE(b_name); 28: 29: Our procedure, however, can access the value of a_name 30: name_print; 31: END; 32: / OUTPUT Jeff Gennick Inside... value of a_name in line 12, the nested block displays the value of a_name in line 18, and in line 30 of the outer block, the nested procedure name_print is called to also print the value of a_name The name_print procedure has access to all other identifiers declared at that same level because it is defined within the outer block The variable b_name is declared in the inner block (see line 15) and can... handles this case by returning a null value A procedure can be nested in the same manner as a function Listing 2.8 shows a simple PL/SQL block illustrating the use of the swapn procedure you saw earlier in Listing 2.5 INPUT LISTING 2.8 Executing the swapn Procedure 1: -2: This is a PL/SQL wrapper 3:- that executes the procedure shown in listing 2.5 4: Demonstration of a nested procedure block 5: DECLARE... illustrate this point INPUT 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: LISTING 2.9 Illustrates the Scope of Various Identifiers DECLARE a_name VARCHAR2(30) := ‘Jeff Gennick’; PROCEDURE name_print IS BEGIN DBMS_OUTPUT.PUT_LINE(a_name); END; BEGIN DBMS_OUTPUT.PUT_LINE(a_name); DECLARE b_name VARCHAR2(30) := ‘Jenny Gennick’; BEGIN DBMS_OUTPUT.PUT_LINE(‘Inside nested block’);... DBMS_OUTPUT.PUT_LINE(‘The names are NOT the same’); END IF; END; / OUTPUT 17: The names are NOT the same 18: 19: PL/SQL procedure successfully completed ANALYSIS What happened here? The same value was assigned to both strings (lines 6 and 7), yet they did not test as being equal (line 10) This occurred because the string contains a number of trailing spaces, whereas the VARCHAR2 string does not Day 3, “Writing PL/SQL. .. Expressions,” talks about the issue in detail CHAR When comparing CHAR strings against VARCHAR2 strings, use the rtrim function to eliminate trailing spaces, as in the following example: Tip IF RTRIM(employee_name_c) = employee_name_v THEN The RTRIM function is one you will learn more about on Day 6, “Using Oracle’s Built -in Functions.” CHAR Subtypes Oracle has one subtype defined for the CHAR datatype, and . PLS_INTEGER instead of BINARY_INTEGER . Tip BINARY_INTEGER Subtypes Oracle has defined four subtypes for the BINARY_INTEGER datatype, as explained in Table. equal (line 10). This occurred because the CHAR string contains a number of trailing spaces, whereas the VARCHAR2 string does not. Day 3, “Writing PL/SQL