Oracle Database 10g The Complete Reference phần 2 ppt

135 424 0
Oracle Database 10g The Complete Reference phần 2 ppt

Đ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

118 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 6 Blind Folio 6:118 If the file already exists, you must use the replace option (abbreviated rep)ofthesave command to save the new query in a file with that name. For this example, the syntax would be save fred.sql rep Alternatively, you could append to the fred.sql file with the command save fred.sql app. store You can use the store command to save your current SQL*Plus environment settings to a file. The following will create a file called my_settings.sql and will store the settings in that file: store set my_settings.sql create If the my_settings.sql file already exists, you can use the replace option instead of create, replacing the old file with the new settings. You could also use the append option to append the new settings to an existing file. Editing Everyone has a favorite editor. Word processing programs can be used with SQL*Plus, but only if you save the files created in them in ASCII format (see your word processor manual for details on how to do this). Editors are just programs themselves. They are normally invoked simply by typing their name at the operating system prompt. On UNIX, it usually looks something like this: > vi fred.sql In this example, vi is your editor’s name, and fred.sql represents the file you want to edit (the start file described previously was used here only as an example—you would enter the real name of whatever file you want to edit). Other kinds of computers won’t necessarily have the > prompt, but they will have something equivalent. If you can invoke an editor this way on your computer, it is nearly certain you can do the same from within SQL*Plus, except that you don’t type the name of your editor, but rather the word edit: SQL> edit fred.sql You should first tell SQL*Plus your editor’s name. You do this while in SQL*Plus by defining the editor, like this: define _editor = "vi" (That’s an underscore before the e in editor.) SQL*Plus will then remember the name of your editor (until you quit SQL*Plus) and allow you to use it anytime you want. See the sidebar “Using login.sql to Define the Editor” for directions on making this happen automatically. P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:09 PM Color profile: Generic CMYK printer profile Composite Default screen host In the unlikely event that none of the editing commands described in the preceding section work, but you do have an editor you’d like to use, you can invoke it by typing this: host vi fred.sql host tells SQL*Plus that this is a command to simply hand back to the operating system for execution. It’s the equivalent of typing vi fred.sql at the operating system prompt. Incidentally, this same host command can be used to execute almost any operating system command from within SQL*Plus, including dir, copy, move, erase, cls, and others. Chapter 6: Basic SQL*Plus Reports and Commands 119 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 6 Blind Folio 6:119 Using login.sql to Define the Editor If you’d like SQL*Plus to define your editor automatically, put the define _editor command in a file named login.sql. This is a special filename that SQL*Plus always looks for whenever it starts up. If it finds login.sql, it executes any commands in the file as if you had entered them by hand. It looks first at the directory you are in when you type SQLPLUS. If it doesn’t find login.sql there, it then looks in the home directory for Oracle. If it doesn’t find login.sql there, it stops looking. You can put virtually any command in login.sql that you can use in SQL*Plus, including both SQL*Plus commands and SQL statements; all of them will be executed before SQL*Plus gives you the SQL prompt. This can be a convenient way to set up your own individual SQL*Plus environment, with all the basic layouts the way you prefer them. Here’s an example of a typical login.sql file: prompt Login.sql loaded. set feedback off set sqlprompt 'What now, boss? ' set sqlnumber off set numwidth 5 set pagesize 24 set linesize 79 define _editor="vi" As of Oracle Database 10 g, Oracle provides three new predefined environment variables: _DATE, _PRIVILEGE (‘AS SYSDBA’, ‘AS SYSOPER’, or blank), and _USER (same value as show user returns). Another file, named glogin.sql, is used to establish default SQL*Plus settings for all users of a database. This file, usually stored in the administrative directory for SQL*Plus, is useful in enforcing column and environment settings for multiple users. The meaning of each of these commands can be found in the Alphabetical Reference section of this book. P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:11 PM Color profile: Generic CMYK printer profile Composite Default screen Adding SQL*Plus Commands Once you’ve saved a SQL statement into a file, such as fred.sql, you can add to the file any SQL*Plus commands you want. Essentially, you can build this file in a similar fashion to activity.sql in Figure 6-3. When you’ve finished working on it, you can exit your editor and be returned to SQL*Plus. start Once you are back in SQL*Plus, test your editing work by executing the file you’ve just edited: start fred.sql All the SQL*Plus and SQL commands in that file will execute, line by line, just as if you’d entered each one of them by hand. If you’ve included a spool and a spool off command in the file, you can use your editor to view the results of your work. This is just what was shown in Figure 6-2—the product of starting activity.sql and spooling its results into activity.lst. To develop a report, use steps like these, in cycles: 1. Use SQL*Plus to build a SQL query interactively. When it appears close to being satisfactory, save it under a name such as test.sql. (The extension .sql is usually reserved for start files, scripts that will execute to produce a report.) 2. Edit the file test.sql using a favorite editor. Add column, break, compute, set, and spool commands to the file. You usually spool to a file with the extension .lst, such as test.lst. Exit the editor. 3. Back in SQL*Plus, the file test.sql is started. Its results fly past on the screen, but also go into the file test.lst. The editor examines this file. 4. Incorporate any necessary changes into test.sql and run it again. 5. Continue this process until the report is correct and polished. Checking the SQL*Plus Environment You saw earlier that the command line editor can’t change SQL*Plus commands, because it can affect only SQL statements—those lines stored in the SQL buffer. You also saw that you can save SQL statements and store environment settings into files, where they can be modified using your own editor. If you’d like to check how a particular column is defined, type column DaysOut without anything following the column name. SQL*Plus will then list all the instructions you’ve given about that column, as shown here: COLUMN DaysOut ON HEADING 'Days!Out' headsep '!' FORMAT 999.99 120 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 6 Blind Folio 6:120 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:11 PM Color profile: Generic CMYK printer profile Composite Default screen If you type just the word column, without any column name following it, then all the columns will be listed. You will see all the columns Oracle sets up by default, plus the ones that you’ve defined: COLUMN Title ON FORMAT a20 word_wrap COLUMN DaysOut ON HEADING 'Days!Out' headsep '!' FORMAT 999.99 COLUMN Name ON FORMAT a20 ttitle, btitle, break, and compute are displayed simply by typing their names, with nothing following. SQL*Plus answers back immediately with the current definitions. The first line in each of the next examples is what you type; the following lines show SQL*Plus’s replies: ttitle ttitle ON and is the following 31 characters: Checkout Log for 1/1/02-3/31/02 btitle btitle ON and is the following 18 characters: from the Bookshelf break break on report nodup on Name skip 1 nodup compute COMPUTE avg LABEL 'avg' OF DaysOut ON Name COMPUTE avg LABEL 'avg' OF DaysOut ON report Looking at those settings (also called parameters ) that follow the set command requires the use of the word show: show headsep headsep "!" (hex 21) show linesize linesize 80 show pagesize pagesize 60 show newpage newpage 0 Chapter 6: Basic SQL*Plus Reports and Commands 121 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 6 Blind Folio 6:121 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:12 PM Color profile: Generic CMYK printer profile Composite Default screen See the Alphabetical Reference section of this book under set and show for a complete list of parameters. The ttitle and btitle settings can be disabled by using the btitle off and ttitle off commands. The following listing shows these commands (note that SQL*Plus does not reply to the commands): ttitle off btitle off The settings for columns, breaks, and computes can be disabled via the clear columns, clear breaks, and clear computes commands. The first line in each example in the following listing is what you type; the lines that follow show how SQL*Plus replies: clear columns columns cleared clear breaks breaks cleared clear computes computes cleared Building Blocks This has been a fairly dense chapter, particularly if SQL*Plus is new to you; yet on reflection, you’ll probably agree that what was introduced here is not really difficult. If Figure 6-3 looked daunting when you began the chapter, look at it again now. Is there any line on it that you don’t understand, or don’t have a sense for what is being done and why? You could, if you wanted, simply copy this file (activity.sql) into another file with a different name and then begin to modify it to suit your own tastes and to query against your own tables. The structure of any reports you produce will, after all, be very similar. There is a lot going on in activity.sql, but it is made up of simple building blocks. This will be the approach used throughout the book. Oracle provides building blocks, and lots of them, but each separate block is understandable and useful. In the previous chapters, you learned how to select data out of the database, choosing certain columns and ignoring others, choosing certain rows based on logical restrictions you set up, and combining two tables to give you information not available from either one on its own. In this chapter, you learned how to give orders that SQL*Plus can follow in formatting and producing the pages and headings of polished reports. In the next several chapters, you’ll change and format your data, row by row. Your expertise and confidence should grow chapter by chapter. By the end of Part II of this book, you should be able to produce very sophisticated reports in short order, to the considerable benefit of your company and yourself. 122 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 6 Blind Folio 6:122 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:13 PM Color profile: Generic CMYK printer profile Composite Default screen ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 7 Blind Folio 7:123 CHAPTER 7 Getting Text Information and Changing It P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:13 PM Color profile: Generic CMYK printer profile Composite Default screen T his chapter introduces string functions, which are software tools that allow you to manipulate a string of letters or other characters. To quickly reference individual functions, look them up by name in the Alphabetical Reference section of this book. This chapter focuses on the manipulation of text strings; to perform word searches (including word stem expansions and fuzzy matches), you should use Oracle Text, as described in Chapter 25. Functions in Oracle work in one of two ways. Some functions create new objects from old ones; they produce a result that is a modification of the original information, such as turning lowercase characters into uppercase. Other functions produce a result that tells you something about the information, such as how many characters are in a word or sentence. NOTE If you are using PL/SQL, you can create your own functions with the create function statement. See Part IV for details. Datatypes Just as people can be classified into different types based on certain characteristics (shy, outgoing, smart, silly, and so forth), different kinds of data can be classified into datatypes based on certain characteristics. Datatypes in Oracle include NUMBER, CHAR (short for CHARACTER), DATE, VARCHAR2, LONG, RAW, LONG RAW, BLOB, CLOB, and BFILE. The first several are probably obvious. The rest are special datatypes that you’ll encounter later. A full explanation of each of these can be found by name or under “Datatypes” in the Alphabetical Reference section of this book. Each datatype is covered in detail in the chapters ahead. As with people, some of the “types” overlap, and some are fairly rare. If the information is of the character (VARCHAR2 or CHAR) type—a mixture of letters, punctuation marks, numbers, and spaces (also called alphanumeric) —you’ll need string functions to modify or inform you about it. Oracle’s SQL provides quite a few such tools. What Is a String? A string is a simple concept: a bunch of things in a line, such as houses, popcorn, pearls, numbers, or characters in a sentence. Strings are frequently encountered in managing information. Names are strings of characters, as in Juan L’Heureaux. Phone numbers are strings of numbers, dashes, and sometimes parentheses, as in (415) 555-2676. Even a pure number, such as 5443702, can be considered as either a number or a string of characters. NOTE Datatypes that are restricted to pure numbers (plus a decimal point and minus sign, if needed) are called NUMBER, and they are not usually referred to as strings. A number can be used in certain ways that a string cannot, and vice versa. 124 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 7 Blind Folio 7:124 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:14 PM Color profile: Generic CMYK printer profile Composite Default screen Strings that can include any mixture of letters, numbers, spaces, and other symbols (such as punctuation marks and special characters) are called character strings, or just character for short. There are two string datatypes in Oracle. CHAR strings are always a fixed length. If you set a value to a string with a length less than that of a CHAR column, Oracle automatically pads the string with blanks. When you compare CHAR strings, Oracle compares the strings by padding them out to equal lengths with blanks. This means that if you compare “character” with “character” in CHAR columns, Oracle considers the strings to be the same. The VARCHAR2 datatype is a variable-length string. The VARCHAR datatype is synonymous with VARCHAR2, but this may change in future versions of Oracle, so you should avoid using VARCHAR. Use CHAR for fixed- length character string fields and VARCHAR2 for all other character string fields. The simple Oracle string functions, explained in this chapter, are shown in Table 7-1. Chapter 7: Getting Text Information and Changing It 125 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 7 Blind Folio 7:125 Function Name Use | | Glues or concatenates two strings together. The | symbol is called a vertical bar or pipe. ASCII Returns the decimal representation in the database character set of the first character of the string. CHR Returns the character having the binary equivalent to the string in either the database character set or the national character set. CONCAT Concatenates two strings together (same as | |). INITCAP Initial capital. Capitalizes the first letter of a word or series of words. INSTR Finds the location of a character in a string. LENGTH Tells the length of a string. LOWER Converts every letter in a string to lowercase. LPAD Left pad. Makes a string a certain length by adding a certain set of characters to the left. LTRIM Left trim. Trims all the occurrences of any one of a set of characters off the left side of a string. NLS_INITCAP Initcap based on the National Language Support (NLS) value. NLS_LOWER Lower based on the NLS value. NLS_UPPER Upper based on the NLS value. NLSSORT Sort based on the national language selected. REGEXP_INSTR, REGEXP_REPLACE, and REGEXP_ SUBSTR INSTR, REPLACE, and SUBSTR for regular expressions. TABLE 7-1. Oracle String Functions P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:14 PM Color profile: Generic CMYK printer profile Composite Default screen Notation Functions are shown with this kind of notation throughout the book: FUNCTION( string [, option ]) The function itself will be in uppercase. The thing it affects (usually a string) will be shown in lowercase italics. Any time the word string appears, it represents either a literal string of characters or the name of a character column in a table. When you actually use a string function, any literal must be in single quotes; any column name must appear without single quotes. Every function has only one pair of parentheses. The value that function works on, as well as additional information you can pass to the function, goes between the parentheses. Some functions have options, parts that are not always required that you can use to make the function work as you want. Options are always shown in square brackets: [ ]. See the discussion on LPAD and RPAD in the following section for an example of how options are used. A simple example of how the LOWER function is printed follows: LOWER( string ) The word “LOWER” with the two parentheses is the function itself, so it is shown here in uppercase; string stands for the actual string of characters to be converted to lowercase, and it’s shown in lowercase italics. Therefore, LOWER('CAMP DOUGLAS') would produce camp douglas 126 Part II: SQL and SQL*Plus ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 7 Blind Folio 7:126 Function Name Use RPAD Right pad. Makes a string a certain length by adding a certain set of characters to the right. RTRIM Right trim. Trims all the occurrences of any one of a set of characters off the right side of a string. SOUNDEX Finds words that sound like the example specified. SUBSTR Substring. Clips out a piece of a string. TREAT Changes the declared type of an expression. TRIM Trims all occurrences of any one of a set of characters off either or both sides of a string. UPPER Converts every letter in a string into uppercase. TABLE 7-1. Oracle String Functions (continued) P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:15 PM Color profile: Generic CMYK printer profile Composite Default screen The string ‘CAMP DOUGLAS’ is a literal, meaning that it is literally the string of characters that the function LOWER is to work on. Oracle uses single quotation marks to denote the beginning and end of any literal string. The string in LOWER also could have been the name of a column from a table, in which case the function would have operated on the contents of the column for every row brought back by a select statement. For example, select City, LOWER(City), LOWER('City') from WEATHER; would produce this result: CITY LOWER(CITY) LOWE LIMA lima city PARIS paris city MANCHESTER manchester city ATHENS athens city CHICAGO chicago city SYDNEY sydney city SPARTA sparta city At the top of the second column, in the LOWER function, CITY is not inside single quotation marks. This tells Oracle that it is a column name, not a literal. In the third column’s LOWER function, ‘CITY’ is inside single quotation marks. This means you literally want the function LOWER to work on the word “CITY” (that is, the string of letters C-I-T-Y), not the column by the same name. Concatenation ( || ) The following notation tells Oracle to concatenate , or stick together, two strings: string || string The strings, of course, can be either column names or literals. Here’s an example: select City||Country from LOCATION; CITY || COUNTRY ATHENSGREECE CHICAGOUNITED STATES CONAKRYGUINEA LIMAPERU MADRASINDIA MANCHESTERENGLAND MOSCOWRUSSIA PARISFRANCE SHENYANGCHINA ROMEITALY TOKYOJAPAN Chapter 7: Getting Text Information and Changing It 127 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 225351-7 / Chapter 7 Blind Folio 7:127 P:\010Comp\Oracle8\351-7\CD\Ventura\book.vp Friday, August 13, 2004 1:45:16 PM Color profile: Generic CMYK printer profile Composite Default screen [...]... GLEN THEODORE HUGGY PHIL FRANK MARY FELICIA FRED PHONE -21 3-555- 022 3 415-555-7530 21 4-555-8383 3 12- 555-1166 707-555-8900 3 12- 555-1414 415-555-68 42 415-555 -21 78 415-555-7387 415-555-75 12 415-555- 625 2 617-555-0 125 603-555 -22 42 2 02- 555-1414 718-555-1638 21 4-555-8383 503-555-7491 To find duplicates, you must force Oracle to compare each last name in the table to all the others in the same table Join the. .. MARY ARNY GLEN THEODORE HUGGY PHIL PHONE -21 3-555- 022 3 415-555-7530 21 4-555-8383 3 12- 555-1166 707-555-8900 3 12- 555-1414 415-555-68 42 415-555 -21 78 415-555-7387 415-555-75 12 415-555- 625 2 617-555-0 125 603-555 -22 42 137 Color profile: Generic CMYK printer profile Composite Default screen 138 Part II: ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 5351-7 / Chapter 7 Blind Folio 7:138 SQL and... In the set ' "THE' In other words, all of the following and many other combinations of the letters will have the same effect when used as the set of an LTRIM or RTRIM: ' "THE' 'HET"' 'E"TH' 'H"TE' 'ET"H' The order of the letters of the set has no effect on how the function works Note, however, that the case of the letters is important Oracle will check the case of both the letters in the set and in the. .. relative to the end of the column, not the end of the string P:\010Comp \Oracle8 \351-7\CD\Ventura\book.vp Friday, August 13, 20 04 1:45 :26 PM 139 Color profile: Generic CMYK printer profile Composite Default screen 140 Part II: ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 5351-7 / Chapter 7 Blind Folio 7:140 SQL and SQL*Plus The following example shows the result of a negative number in the SUBSTR... this) and then sliding over two steps to the right (where his first name begins) The following illustration shows how the INSTR function (plus 2) serves as the start for the SUBSTR function: SUBSTR(Author, INSTR(Author,',') P:\010Comp \Oracle8 \351-7\CD\Ventura\book.vp Friday, August 13, 20 04 1:45 :29 PM ) Add 2 to it to move to the beginning of the author‘s first name Find the location of the comma BONHOEFFER,... 555 -21 78 555-7387 555-75 12 555- 625 2 The use of negative numbers in the SUBSTR function also works Normally, the position value you specify for the starting position is relative to the start of the string When you use a negative number for the position value, it is relative to the end of the string For example, SUBSTR(Phone,-4) would use the fourth position from the end of the Phone column’s value as... Composite Default screen 128 Part II: ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 5351-7 / Chapter 7 Blind Folio 7: 128 SQL and SQL*Plus SYDNEYAUSTRALIA SPARTAGREECE MADRIDSPAIN Here, the cities vary in width from 4 to 12 characters The countries push right up against them This is just how the concatenate function is supposed to work: It glues columns or strings together with no spaces in... BONHOEFFER CHESTERTON RUTH WHITEHEAD CROOKES Next, look at the one that clips from two positions past the comma to the end of the string: select Author, SUBSTR(Author,INSTR(Author,',') +2) from MAGAZINE; P:\010Comp \Oracle8 \351-7\CD\Ventura\book.vp Friday, August 13, 20 04 1:45 :28 PM ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 5351-7 / Chapter 7 Blind Folio 7:143 Color profile: Generic... substring of the phone number, starting at position 5 and going to the end of the string Doing this eliminates the area code Of course, SUBSTR(Phone,5) has exactly the same effect as the following: SUBSTR(Phone,5,8) P:\010Comp \Oracle8 \351-7\CD\Ventura\book.vp Friday, August 13, 20 04 1:45 :25 PM Color profile: Generic CMYK printer profile Composite Default screen ORACLE Series TIGHT / Oracle Database 10g: TCR... and it can be broken down the same way Bonhoeffer can provide the example The first part looks like this: SUBSTR(Author,INSTR(Author,',') +2) This tells SQL to get the SUBSTR of Author starting two positions to the right of the comma and going to the end This will clip out DIETRICH the author’s first name The beginning of the author’s first name is found by locating the comma at the end of his last name . 415-555-75 12 EDGAR THEODORE 415-555- 625 2 HARDIN HUGGY 617-555-0 125 HILD PHIL 603-555 -22 42 Chapter 7: Getting Text Information and Changing It 137 ORACLE Series TIGHT / Oracle Database 10g: TCR. Returns the decimal representation in the database character set of the first character of the string. CHR Returns the character having the binary equivalent to the string in either the database. Commands 121 ORACLE Series TIGHT / Oracle Database 10g: TCR / Loney / 22 5351-7 / Chapter 6 Blind Folio 6: 121 P:10Comp Oracle8 351-7CDVenturaook.vp Friday, August 13, 20 04 1:45: 12 PM Color

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

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

  • Đang cập nhật ...

Tài liệu liên quan