Oracle PL/SQL for dummies phần 7 ppsx

44 443 0
Oracle PL/SQL for dummies phần 7 ppsx

Đ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

SUBSTR is needed if you want to retrieve part of existing string, as shown here: v_tx:= substr(string, start position[,number of chars]); The start position could be either a positive or negative integer. This would start counting the position from the beginning or from the end of the string, as shown here: SQL> declare 2 v1_tx VARCHAR2(5):=’ABCDE’; 3 v2_tx VARCHAR2(5); 4 begin 5 v2_tx:=substr(v1_tx,2); 6 DBMS_OUTPUT.put_line(v2_tx); 7 v2_tx:=substr(v1_tx,-2); 8 DBMS_OUTPUT.put_line(v2_tx); 9 end; 10 / BCDE DE PL/SQL procedure successfully completed. SQL> As shown in these examples, you can omit the third parameter (requested number of characters). In that case, Oracle returns everything from the point you specified to the end of the string. If your starting point is more than the total number of characters in the string, Oracle returns NULL. The number of characters requested from the string might not always be the length of the resulting string. It could be less, because you might request more characters than the string has. In that case, Oracle just returns everything up to the end of the string, as shown in Listing 10-18. Listing 10-18: Using SUBSTR SQL> declare 2 v1_tx VARCHAR2(5):=’ABCDE’; 3 v2_tx VARCHAR2(5); 4 begin 5 v2_tx:=substr(v1_tx,2,2); ➞ 5 6 DBMS_OUTPUT.put_line(v2_tx); 7 v2_tx:=substr(v1_tx,2,7); ➞ 7 8 DBMS_OUTPUT.put_line(v2_tx); 9 end; 10 / BC ➞ 11 BCDE ➞ 12 PL/SQL procedure successfully completed. SQL> 246 Part IV: PL/SQL Data Manipulations 17_599577 ch10.qxp 5/1/06 12:23 PM Page 246 Additional information about Listing 10-18 is shown here: ➞ 5, 11 The code works perfectly because you requested two characters and two characters were returned. ➞ 7, 12 This line requested 7 characters, and 4 were returned because only 5 characters were in the original string. The function INSTR allows you to locate one string/character in the other one. You can declare it as shown here: v_nr:= instr(string,substring[,position,occurrence]); At the simplest level, INSTR returns the number of characters in the original string where the desired substring starts. But you can also specify the posi- tion from which you want the search to start (by default from the first charac- ter) and what occurrence of the desired string is required (by default, the first one), as shown in Listing 10-19. Listing 10-19: Using INSTR SQL> declare 2 v1_tx VARCHAR2(20):=’Hello, World!’; 3 v_nr binary_integer; 4 begin 5 v_nr:= instr (v1_tx,’l’); ➞ 5 6 DBMS_OUTPUT.put_line(v_nr); 7 v_nr:= instr (v1_tx,’l’,-2); ➞ 7 8 DBMS_OUTPUT.put_line(v_nr); 9 v_nr:= instr (v1_tx,’l’,2,2); ➞ 9 10 DBMS_OUTPUT.put_line(v_nr); 11 end; 12 / 3 ➞ 13 11 ➞ 14 4 ➞ 15 PL/SQL procedure successfully completed. SQL> Listing 10-19 works as shown here: ➞ 5, 13 There are three occurrences of the letter ‘l’ in the original string. In the first case, you’re getting the position of first letter starting from the beginning (default). ➞ 7, 14 These lines of code retrieve the first occurrence of the letter ‘l’ starting from the second character at the end in reverse order. You can have both positive and negative starting positions as in SUBSTR, but here it means not only the starting point, but also the direction of the search. 247 Chapter 10: Basic Datatypes 17_599577 ch10.qxp 5/1/06 12:23 PM Page 247 ➞ 9, 15 These lines get the second occurrence of the letter ‘l’, starting from the second character. You’ll often use both SUBSTR and INSTR at the same time, especially for parsing text. For example, to print out the last word in the string, you can use the following code: SQL> declare 2 v1_tx VARCHAR2(20):=’Hello to everybody’; 3 v2_tx VARCHAR2(20); 4 begin 5 v2_tx:= substr (v1_tx, instr (v1_tx,’ ‘,-1)+1); 6 DBMS_OUTPUT.put_line(v2_tx); 7 end; 8 / everybody PL/SQL procedure successfully completed. SQL> Even though this is an oversimplified case (you are taking everything from the last blank character to the end), it is absolutely correct. First, you need to find the position of the last space character by using INSTR, and second, you need to use SUBSTR to grab the rest of the string — starting with the next character from the one you found and going to the end of the original string. REPLACE and TRANSLATE The REPLACE and TRANSLATE functions allow you to transform text by using the specified pattern shown here: v_tx:= replace(string,search[,replacement]); v_tx:= translate(string, search, replacement); Although these functions look similar, there is a major difference. The REPLACE function changes one string to another string, as shown here: SQL> declare 2 v1_tx VARCHAR2(20):=’To be or not to be’; 3 v2_tx VARCHAR2(20); 4 begin 5 DBMS_OUTPUT.put_line(‘Before: ‘ || v1_tx); 6 v2_tx:= replace (v1_tx,’be’,’eat’); 7 DBMS_OUTPUT.put_line(‘After: ‘ || v2_tx); 8* end; 9 / Before: To be or not to be After: To eat or not to eat PL/SQL procedure successfully completed. SQL> 248 Part IV: PL/SQL Data Manipulations 17_599577 ch10.qxp 5/1/06 12:23 PM Page 248 If you don’t specify the third parameter, Oracle just removes all occurrences of the search string. This is very useful if you want to remove all the spaces from the text. The TRANSLATE function takes search and replacement strings and creates character-to-character maps (the first character from the search string should be replaced with first character from the replacement string, and so on), as shown here: SQL> declare 2 v1_tx VARCHAR2(20):=’To be or not to be’; 3 v2_tx VARCHAR2(20); 4 begin 5 v2_tx:= translate (v1_tx,’bo ‘,’BO’); 6 DBMS_OUTPUT.put_line(v2_tx); 7 end; 8 / TOBeOrnOttOBe PL/SQL procedure successfully completed. SQL> If you have more characters in the source string than in the replacement string, those characters are removed. As in the example, because the replace- ment string has only two characters, the third character from the source string is gone. No spaces appear in the result. With the TRANSLATE function, the third parameter (the replacement charac- ters) can’t be NULL or an empty string. Otherwise, the result is always NULL. *PAD and *TRIM A number of functions allow you to either add (PAD) or remove (TRIM) char- acters to an existing string: LPAD/LTRIM do it from the left side of the string, RPAD/PTRIM from the right side. Also, a wrapper function, TRIM, allows you to select the trimming mode (left side – leading /right side – trailing /both) as shown in Listing 10-20. Listing 10-20: Using LPAD and LTRIM v_tx:= lpad(string,length,extra string); v_tx:= ltrim(string [,character]); v_tx:= trim(LEADING|TRAILING|BOTH character from string); SQL> declare 2 v1_tx VARCHAR2(20):=’Hello!’; 3 v2_tx VARCHAR2(20); 4 v3_tx VARCHAR2(20); 5 begin (continued) 249 Chapter 10: Basic Datatypes 17_599577 ch10.qxp 5/1/06 12:23 PM Page 249 Listing 10-20 (continued) 6 v2_tx:= rpad(lpad(v1_tx,10,’*’),15,’*’); ➞ 6 7 DBMS_OUTPUT.put_line(v2_tx); 8 9 v3_tx:= trim (both ‘*’ from v2_tx); ➞ 9 10 DBMS_OUTPUT.put_line(v3_tx); 11 v3_tx:= trim (leading ‘*’ from v2_tx); ➞ 11 12 DBMS_OUTPUT.put_line(v3_tx); 13 v3_tx:= trim (trailing ‘*’ from v2_tx); ➞ 13 14 DBMS_OUTPUT.put_line(v3_tx); 15 end; 16 / ****Hello!***** Hello! Hello!***** ****Hello! PL/SQL procedure successfully completed. SQL> Here’s what you see in Listing 10-20: ➞ 6 This code pads the original string with * from the left and right sides. ➞ 9 This code represents the most popular way of using the function TRIM by trimming specified character from both sides. ➞ 11 This code represents trimming of leading characters using exactly the same functionality as LTRIM. ➞ 13 This code represents trimming of trailing characters using exactly the same functionality as RTRIM. Unless you are using Oracle 8i, the TRIM function is recommended instead of the older LTRIM/RTRIM because it provides greater flexibility and readability of the code. Extending your options with regular expressions In 10g, Oracle introduced regular expressions, which allow you to search for patterns in string data by using a very rich syntax. This syntax is becoming standard throughout the IT industry. Regular expressions cannot be used as parameters in the standard Oracle built-in text search functions: LIKE, SUBSTR, INSTR, and REPLACE. Instead, 250 Part IV: PL/SQL Data Manipulations 17_599577 ch10.qxp 5/1/06 12:23 PM Page 250 regular expressions have their own versions of the same functions: REGEXP_ LIKE, REGEXP_SUBSTR, REGEXP_INSTR, and REGEXP_REPLACE. As an example, in regular expressions, the special character | defines an OR condition for the characters surrounding it, as shown here: SQL> declare 2 v1_tx VARCHAR2(2000):=’*ABC*BBC*’; 3 begin 4 DBMS_OUTPUT.put_line(‘First hit:’|| 5 REGEXP_INSTR(V1_TX,’A|BBC’,1,1)); ➞ 5 6 DBMS_OUTPUT.put_line(‘Second hit:’|| 7 REGEXP_INSTR(V1_TX,’A|BBC’,1,2)); ➞ 7 8 end; 9 / First hit:2 Second hit:6 PL/SQL procedure successfully completed. ➞ 5, 7 These lines search for either ‘ABC’ or ‘BBC’ in the specified string. A detailed discussion of regular expressions is beyond the scope of this book, If you need to perform advanced processing of textual information, a good place to start is Oracle Regular Expressions Pocket Reference, by Jonathan Gennick and Peter Linsley (O’Reilly). 251 Chapter 10: Basic Datatypes 17_599577 ch10.qxp 5/1/06 12:23 PM Page 251 252 Part IV: PL/SQL Data Manipulations 17_599577 ch10.qxp 5/1/06 12:23 PM Page 252 Chapter 11 Advanced Datatypes In This Chapter ᮣ Working with large objects (LOBs) ᮣ Enforcing standards with user-defined subtypes ᮣ Defining datatypes ᮣ Creating collections ᮣ Collecting data with bulk operations T o be able to handle many of the complex programming situations that can arise in building database systems, Oracle includes some advanced datatypes and ways to handle large objects, user-defined types and subtypes, and collections. It is important to understand how to use these datatypes correctly and effi- ciently in your code, and in the sections in this chapter, we show you how. Handling Large Objects in the Database Less-experienced database professionals might think that the three major datatypes (DATE, NUMBER, VARCHAR2) are enough to build most systems. However, this is rarely the case. In modern systems, you might want to store pictures, movies, documents, and sounds. The basic Oracle character datatype (VARCHAR2) can hold only 4,000 characters (about the size of a page of text). Imagine that you want to create an online shopping catalog of electronic goods. Each record should contain the name of the item, the full text of the user manual, a picture of the front page of the manual, and a reference to the original text file with the manual stored on the server. Oracle technology provides the solution to this problem with a class of datatypes designed to store up to 8-128TB of binary/textual information. These datatypes are called LOBs (or large objects). However, in some cases, (depending upon the environment) you are restricted to 4GB. 18_599577 ch11.qxp 5/1/06 12:15 PM Page 253 When using large objects, the issues of performance and storage always arise. To address these concerns, Oracle provides two options: ߜ You can store the large objects internally, within the database itself (called internal large objects in this book). If you store large objects in the database, they can be retrieved quickly, and you don’t have to worry about managing individual files. However, with these objects in the data- base, the database will get very large. If you don’t use a good backup utility, it can take hours (or even days) to do a full database backup. ߜ You can keep the objects in the file system and just store the filenames in the database (external large objects). Storing large objects in the file system has its own risks. Some operating systems perform very slowly when thousands of files are in a single directory. And you have to worry about people moving, deleting, or otherwise changing the contents of the objects outside your database-based programs. The database is restricted to read-only access to these objects. Using internal large objects (CLOB, BLOB) With internal large objects, Oracle stores the data within the database. However, the data is physically stored separately from the rest of the columns in the table, and the table actually contains pointers to the data in the LOBs. Two types of internal large objects exist: ߜ CLOB (character large object): The most common use of CLOBs is to store large amounts of character (text) information. ߜ BLOB (binary large object): BLOBs are used to store binary (mostly video/audio) information in the database. When saying “CLOB” or “BLOB” out loud, some people say see-lob and bee- lob, and others say klob and blob. You should be able to recognize either pronunciation. Creating pointers with external large objects With external large objects, the pointer (also called LOB locator) to the object is stored in a BFILE column in the database. The pointer is an internal 254 Part IV: PL/SQL Data Manipulations 18_599577 ch11.qxp 5/1/06 12:15 PM Page 254 reference that Oracle can understand, indicating the location where the real data is stored (in that case to the file in file system). It provides read-only access to files on the server. The most common use for BFILE is to provide a convenient way of referencing objects maintained outside the database (for example, a collection of photos). Using the example of an online shopping catalog for electronic goods, you can use the advanced datatypes to create a table, as shown here. create table catalog (item_id number, name_tx VARCHAR2(2000), manual_cl CLOB, firstpage_bl BLOB, mastertxt_bf BFILE); The amount of information needed to work with large objects is beyond the scope of this book. We provide some simple examples here, but you can find more information in the Oracle Database Documentation library available online in the section Oracle Database Application Developer’s Guide - Large Objects of the OTN Web site (www.oracle.com/technology/index.html). Working with Large Objects The following sections explain the steps needed to create a system such as the online catalog of electronic goods mentioned earlier. Populating BFILE Oracle accesses files on the server by using a directory, which is just a pointer to an operating system folder. If you’re in a normal Oracle working environment, your organization’s DBA will probably have to create a direc- tory for you. Assuming that a folder C:\IO exists on your server, and you want to call that folder IO within Oracle, the DBA would execute the follow- ing SQL commands: create directory IO as ‘C:\IO’; grant read, write on directory IO to public; Now, when you refer to IO in any commands, you’re referring to the C:\IO folder in the file system. 255 Chapter 11: Advanced Datatypes 18_599577 ch11.qxp 5/1/06 12:15 PM Page 255 [...]... where empNo =73 69; SMITH select * into v_emp2_rec from emp where empNo =74 99; ALLEN ➞5 ➞10 Chapter 11: Advanced Datatypes v_emp1_rec.empNo: =74 99; v_emp2_rec.empNo: =73 69; update emp set row = where empNo update emp set row = where empNo end; v_emp1_rec = 74 99; SMITH v_emp2_rec = 73 69; ALLEN ➞12 ➞13 ➞16 ➞20 The following list breaks down some of the lines from Listing 11-12: ➞5–10 Collects all information... It is always a challenge to create and enforce standards for different teams working on the same project For example, one group might define large text 259 260 Part IV: PL/SQL Data Manipulations variables as VARCHAR2(2000) while another uses VARCHAR2(4000) These types of inconsistencies can cause problems However, Oracle can help resolve these issues with a PL/SQL element called a subtype The idea... Datatypes The preceding section describes how you can create your own subtypes as more specialized versions of existing Oracle datatypes In addition, it is possible to create entirely new types Some user-defined types are for PL/SQL only, and some can be used in both PL/SQL and SQL You can create PL/SQL datatypes in the declaration portions of procedures, functions, root anonymous blocks, package bodies, and... from the implicit cursor into that variable 7 9 Uses the new type As shown above, the way to reference fields in the record type variables is by using variable.attribute (as in line 11) An implicit declaration uses an existing table, view, or cursor as a reference An example is shown in Listing 11 -7 (See Chapter 6 for additional information) Listing 11 -7: Implicit Declaration declare v_emp_rec emp%ROWTYPE;... LOB via the pointer 7 The changes from Listing 11-2 are minor EMPTY_BLOB ( ) creates a new CLOB pointer in the table Performing basic string operations on CLOBs You can use many regular string operations on CLOBs (search for the patterns, get length, get part of the code, and so on) to create advanced application logic For example, you can implement a search or indexing routine for all large text files... elements in the collection as shown by the output on line 11, which proves that there are indeed only 12 elements ➞12–13 The creation of the last element (for the NULL value) is a bit tricky Even though the size of the array is declared, Oracle 273 274 Part IV: PL/SQL Data Manipulations doesn’t create all the elements of the array automatically You need to create the new instance of the object by using the... ; 275 276 Part IV: PL/SQL Data Manipulations Deleting internal elements from a collection At first glance, nested tables look exactly like arrays without an upper limit However, there is one major difference: Even at the creation point, nested tables have consecutive subscripts; it is possible to delete internal (not only the last) elements afterwards, as shown in Listing 11- 17 Listing 11- 17: Creating... DATE) return emp2_nt is v_emp2_nt emp2_nt:=emp2_nt(); cursor c_emp is select * from emp; begin for r_emp in c_emp loop if i_deptNo is null then if i_hireDate is null or to_char(i_hireDate,’mm’)= to_char(r_emp.hireDate,’mm’) then v_emp2_nt.extend; v_emp2_nt(v_emp2_nt.last):= ➞5 (continued) 277 278 Part IV: PL/SQL Data Manipulations Listing 11-18 (continued) emp2_oty(r_emp.empNo, r_emp.eName, r_emp.deptno);... select ‘Income:’||t.f_getIncome_nr() into v_out_tx from t_emp t where t.empno=100; end; 7 ➞8 ➞11 ➞15 ➞ 17 The following details are relevant to Listing 11-14: 7 8 Inserts the object as a whole element (because in this case, the object is a record) ➞11–13 Updates table columns as if they were normal columns ➞15– 17 Calls object methods directly from SQL To use this functionality, you need to create an... Although you can store almost everything in database tables, this isn’t the most efficient way of processing data Very often you need to create structures and 271 272 Part IV: PL/SQL Data Manipulations process sets of data in memory In the Oracle environment, these structures are called collections A collection is an ordered group of elements, all of the same type, addressed by a unique subscript Because . DBMS_OUTPUT.put_line(v2_tx); 7 v2_tx:=substr(v1_tx,2 ,7) ; ➞ 7 8 DBMS_OUTPUT.put_line(v2_tx); 9 end; 10 / BC ➞ 11 BCDE ➞ 12 PL/SQL procedure successfully completed. SQL> 246 Part IV: PL/SQL Data Manipulations 17_ 599 577 . Linsley (O’Reilly). 251 Chapter 10: Basic Datatypes 17_ 599 577 ch10.qxp 5/1/06 12:23 PM Page 251 252 Part IV: PL/SQL Data Manipulations 17_ 599 577 ch10.qxp 5/1/06 12:23 PM Page 252 Chapter 11 Advanced. successfully completed. SQL> 248 Part IV: PL/SQL Data Manipulations 17_ 599 577 ch10.qxp 5/1/06 12:23 PM Page 248 If you don’t specify the third parameter, Oracle just removes all occurrences of

Ngày đăng: 08/08/2014, 20:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan