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

OCA: Oracle Database 11g Administrator Certified Associate- P3

50 372 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

Định dạng
Số trang 50
Dung lượng 631,15 KB

Nội dung

Writing Simple Queries  31 > (Greater Than) The > operator evaluates to TRUE if the left side (expression or value) of the operator is greater than the right side of the operator SELECT first_name || ‘ ‘ || last_name “Name”, commission_pct FROM employees WHERE commission_pct > 35; Name COMMISSION_PCT -John Russell = 35; 32  Chapter 1    Introducing SQL n Name COMMISSION_PCT -John Russell Janette King 35 Patrick Sully 35 Allan McEwen 35 ANY or SOME You can use the ANY or SOME operator to compare a value to each value in a list or subquery The ANY and SOME operators always must be preceded by one of the following comparison operators: =, !=, , = SELECT first_name || ‘ ‘ || last_name “Name”, department_id FROM employees WHERE department_id = ALL (80, 90, 100); Name DEPARTMENT_ID - Nancy Greenberg 100 Daniel Faviet 100 John Chen 100 Ismael Sciarra 100 Jose Manuel Urman 100 Luis Popp 100 Shelley Higgins 110 William Gietz 110 rows selected For all the comparison operators discussed, if one side of the operator is NULL, the result is NULL Writing Simple Queries  33 Logical Operators Logical operators are used to combine the results of two comparison conditions (compound conditions) to produce a single result or to reverse the result of a single comparison NOT, AND, and OR are the logical operators When a logical operator is applied to NULL, the result is UNKNOWN UNKNOWN acts similarly to FALSE; the only difference is that NOT FALSE is TRUE, whereas NOT UNKNOWN is also UNKNOWN NOT You can use the NOT operator to reverse the result It evaluates to TRUE if the operand is FALSE, and it evaluates to FALSE if the operand is TRUE NOT returns NULL if the operand is NULL WHERE !(department_id >= 30) * ERROR at line 3: SELECT first_name, department_id FROM employees WHERE not (department_id >= 30); FIRST_NAME DEPARTMENT_ID Jennifer 10 Michael 20 Pat 20 AND The AND operator evaluates to TRUE if both operands are TRUE It evaluates to FALSE if either operand is FALSE Otherwise, it returns NULL SELECT FROM WHERE AND first_name, salary employees last_name = ‘Smith’ salary > 7500; FIRST_NAME SALARY -Lindsey 8000 34  Chapter 1    Introducing SQL n OR The OR operator evaluates to TRUE if either operand is TRUE It evaluates to FALSE if both operands are FALSE Otherwise, it returns NULL SELECT FROM WHERE OR first_name, last_name employees first_name = ‘Kelly’ last_name = ‘Smith’; FIRST_NAME -Lindsey William Kelly LAST_NAME Smith Smith Chung Logical Operator Truth Tables The following tables are the truth tables for the three logical operators Table 1.7 is a truth table for the AND operator Ta b l e    ​ AND Truth Table  ​ AND TRUE FALSE UNKNOWN TRUE TRUE FALSE UNKNOWN FALSE FALSE FALSE FALSE UNKNOWN UNKNOWN FALSE UNKNOWN Table 1.8 is the truth table for the OR operator Ta b l e    ​ OR Truth Table  ​ OR TRUE FALSE UNKNOWN TRUE TRUE TRUE TRUE FALSE TRUE FALSE UNKNOWN UNKNOWN TRUE UNKNOWN UNKNOWN Writing Simple Queries  35 Table 1.9 is the truth table for the NOT operator Ta b l e    ​ NOT Truth Table  ​ NOT TRUE FALSE FALSE TRUE UNKNOWN UNKNOWN Other Operators In the following sections, I will discuss all the operators that can be used in the WHERE clause of the SQL statement that were not discussed earlier IN and NOT IN You can use the IN and NOT IN operators to test a membership condition IN is equivalent to the =ANY operator, which evaluates to TRUE if the value exists in the list or the result set from a subquery The NOT IN operator is equivalent to the !=ALL operator, which evaluates to TRUE if the value does not exist in the list or the result set from a subquery The following examples demonstrate how to use these two operators: SELECT first_name, last_name, department_id FROM employees WHERE department_id IN (10, 20, 90); FIRST_NAME -Steven Neena Lex Jennifer Michael Pat LAST_NAME DEPARTMENT_ID - -King 90 Kochhar 90 De Haan 90 Whalen 10 Hartstein 20 Fay 20 rows selected SELECT first_name, last_name, department_id FROM employees WHERE department_id NOT IN (10, 30, 40, 50, 60, 80, 90, 110, 100); 36  Chapter 1    Introducing SQL n FIRST_NAME -Michael Pat Hermann SQL> LAST_NAME DEPARTMENT_ID Hartstein 20 Fay 20 Baer 70 When using the NOT IN operator, if any value in the list or the result returned from the subquery is NULL, the NOT IN condition is evaluated to FALSE For example, last_name not in (‘Smith’, ‘Thomas’, NULL) evaluates to last_name != ‘Smith’ AND last_name != ‘Thomas’ AND last_name != NULL Any comparison on a NULL value results in NULL So, the previous condition does not return any row even through there may be some rows with LAST_NAME as Smith or Thomas BETWEEN You can use the BETWEEN operator to test a range BETWEEN A AND B evaluates to TRUE if the value is greater than or equal to A and less than or equal to B If NOT is used, the result is the reverse The following example lists all the employees whose salary is between $5,000 and $6,000: SELECT first_name, last_name, salary FROM employees WHERE salary BETWEEN 5000 AND 6000; FIRST_NAME -Bruce Kevin Pat LAST_NAME SALARY - -Ernst 6000 Mourgos 5800 Fay 6000 EXISTS The EXISTS operator is always followed by a subquery in parentheses EXISTS evaluates to TRUE if the subquery returns at least one row The following example lists the employees who work for the administration department Here is an example of using EXISTS Don’t worry if you not understand the SQL for now; subqueries are discussed in detail in Chapter 4, “Using Joins and Subqueries.” SELECT last_name, first_name, department_id FROM employees e WHERE EXISTS (select FROM departments d Writing Simple Queries  WHERE AND 37 d.department_id = e.department_id d.department_name = ‘Administration’); LAST_NAME FIRST_NAME DEPARTMENT_ID Whalen Jennifer 10 SQL> IS NULL and IS NOT NULL To find the NULL values or NOT NULL values, you need to use the IS NULL operator The = or != operator will not work with NULL values IS NULL evaluates to TRUE if the value is NULL IS NOT NULL evaluates to TRUE if the value is not NULL To find the employees who not have a department assigned, use this query: SELECT last_name, department_id FROM employees WHERE department_id IS NULL; LAST_NAME DEPARTMENT_ID - Grant SQL> SELECT last_name, department_id FROM employees WHERE department_id = NULL; no rows selected LIKE Using the LIKE operator, you can perform pattern matching The pattern-search character % is used to match any character and any number of characters The pattern-search character _ is used to match any single character If you are looking for the actual character % or _ in the pattern search, you can include an escape character in the search string and notify Oracle using the ESCAPE clause The following query searches for all employees whose first name begins with Su and last name does not begin with S: SELECT FROM WHERE AND first_name, last_name employees first_name LIKE ‘Su%’ last_name NOT LIKE ‘S%’; 38  Chapter 1    Introducing SQL n FIRST_NAME -Sundar Sundita Susan LAST_NAME Ande Kumar Mavris The following example looks for all JOB_ID values that begin with AC_ Since _ is a pattern-matching character, you must qualify it with an escape character Oracle does not have a default escape character SELECT job_id, job_title FROM jobs WHERE job_id like ‘AC\_%’ ESCAPE ‘\’; JOB_ID -AC_MGR AC_ACCOUNT JOB_TITLE Accounting Manager Public Accountant Table 1.10 shows more examples of pattern matching Ta b l e   1  ​ Pattern-Matching Examples  ​ Pattern Matches Does Not Match %SONI_1 SONIC1, ULTRASONI21 SONICS1, SONI315 _IME TIME, LIME IME, CRIME \%SONI_1 ESCAPE ‘\’ %SONIC1, %SONI91 SONIC1, ULTRASONIC1 %ME\_ _ _LE ESCAPE ‘\’ CRIME_FILE, TIME_POLE CRIMESPILE, CRIME_ALE Sorting Rows The SELECT statement may include the ORDER BY clause to sort the resulting rows in a specific order based on the data in the columns Without the ORDER BY clause, there is no guarantee that the rows will be returned in any specific order If an ORDER BY clause is specified, by default the rows are returned by ascending order of the columns specified If you need to sort the rows in descending order, use the keyword DESC next to the column name You can specify the keyword ASC to explicitly state to sort in ascending order, although it is the Writing Simple Queries  default The ORDER BY clause follows the FROM clause and the WHERE clause in the SELECT statement To retrieve all employee names of department 90 from the EMPLOYEES table ordered by last name, use this query: SELECT first_name || ‘ ‘ || last_name “Employee Name” FROM employees WHERE department_id = 90 ORDER BY last_name; Employee Name -Lex De Haan Steven King Neena Kochhar SQL> You can specify more than one column in the ORDER BY clause In this case, the result set will be ordered by the first column in the ORDER BY clause, then the second, and so on Columns or expressions not used in the SELECT clause can also be used in the ORDER BY clause The following example shows how to use DESC and multiple columns in the ORDER BY clause: SELECT first_name, hire_date, salary, manager_id mid FROM employees WHERE department_id IN (110,100) ORDER BY mid ASC, salary DESC, hire_date; FIRST_NAME -Shelley Nancy Daniel John Jose Manuel Ismael Luis William rows selected SQL> HIRE_DATE SALARY MID - -07-JUN-94 12000 101 17-AUG-94 12000 101 16-AUG-94 9000 108 28-SEP-97 8200 108 07-MAR-98 7800 108 30-SEP-97 7700 108 07-DEC-99 6900 108 07-JUN-94 8300 205 39 40  Chapter 1    Introducing SQL n You can use column alias names in the ORDER BY clause If the DISTINCT keyword is used in the SELECT clause, you can use only those columns listed in the SELECT clause in the ORDER BY clause If you have used any operators on columns in the SELECT clause, the ORDER BY clause also should use them Here is an example: SELECT DISTINCT ‘Region ‘ || region_id FROM countries ORDER BY region_id; ORDER BY region_id * ERROR at line 3: ORA-01791: not a SELECTed expression SELECT DISTINCT ‘Region ‘ || region_id FROM countries ORDER BY ‘Region ‘ || region_id; ‘REGION’||REGION_ID Region Region Region Region Not only can you use the column name or column alias to sort the result set of a query, but you can also sort the results by specifying the position of the column in the SELECT clause This is useful if you have a lengthy expression in the SELECT clause and you need the results sorted on this value The following example sorts the result set using positional values: SELECT first_name, hire_date, salary, manager_id mid FROM employees WHERE department_id IN (110,100) ORDER BY 4, 2, 3; FIRST_NAME HIRE_DATE SALARY MID - -Shelley 07-JUN-94 12000 101 66  Chapter 2    Using Single-Row Functions n FIRST_NAME SALARY COMMISSION_PCT COMPENSATION -TJ 2100 Trenna 3500 Taylor 9600 11520 Timothy 2900 You see that only Taylor had the total compensation calculated in the SQL; all others have their total compensation as NULL This is because any operation on NULL results in a NULL You can use the NVL function to substitute a zero in place of any NULL you encounter, like this: SELECT first_name, salary, commission_pct, salary + (salary * NVL(commission_pct,0)) compensation FROM employees WHERE first_name LIKE ‘T%’; FIRST_NAME SALARY COMMISSION_PCT COMPENSATION -TJ 2100 2100 Trenna 3500 3500 Tayler 9600 11520 Timothy 2900 2900 When you used the NVL function to substitute zero for NULL, you got the total compensation calculated correctly For the employees who not have a commission, the salary and compensation are the same NVL2 The function NVL2 is a variation of NVL NVL2 takes three arguments, NVL2(x1, x2, x3), where x1 , x2, and x3 are expressions NVL2 returns x3 if x1 is NULL, and x2 if x1 is not NULL For the example presented in the previous section, you could also use the NVL2 function and write the code a bit differently: SELECT first_name, salary, commission_pct, NVL2(commission_pct, salary + salary * commission_pct, salary) compensation FROM employees WHERE first_name LIKE ‘T%’; FIRST_NAME SALARY COMMISSION_PCT COMPENSATION -TJ 2100 2100 Trenna 3500 3500 Tayler 9600 11520 Timothy 2900 2900 Single-Row Function Fundamentals  67 Using the NVL2 function, if COMMISSION_PCT is not NULL, then salary + salary * commission_pct is returned If COMMISSION_PCT is NULL, then just SALARY is returned The NVL function allows you to perform some value substitution for NULLs The NVL2 function, on the other hand, allows you to implement an IF…THEN…ELSE construct based on the nullity of data Both are useful tools to deal with NULL values Be prepared for a possible exam question that tests your knowledge of when to use an NVL function in a calculation Such a question probably won’t mention NVL and may not look like it is testing your knowledge of NULLs If sample data is given as an exhibit, be sure to look for data columns with NULL values and whether they are used in the SQL presented to you COALESCE COALESCE is a generalization of the NVL function COALESCE(exp_list) takes more than one argument, where exp_list is a list of arguments separated by comma This function returns the first non- NULL value in exp_list If all expressions in exp_list are NULL, then NULL is returned Each expression in exp_list should be the same datatype, or else Oracle tries to convert them implicitly For example, COALESCE(x1, x2, x3) would be evaluated as the following: NN If x1 is NULL, check x2, or else return x1 Stop NN If x2 is NULL, check x3, or else return x2 Stop NN If x3 is NULL, return NULL, or else return x3 Stop Consider the following example The objective is to find the total salary based on COMMISSION_PCT If COMMISSION_PCT is not NULL, calculate SALARY using COMMISSION_PCT If COMMISSION_PCT is NULL, then give $100 as commission If SALARY is not defined (NULL) for an employee, give the minimum salary of $900 SELECT last_name, salary, commission_pct AS comm, COALESCE(salary+salary*commission_pct, salary+100, 900) compensation FROM employees WHERE last_name like ‘T%’; LAST_NAME SALARY COMM COMPENSATION - -Taylor 8600 10320 Taylor 3200 3300 Tobias 900 Tucker 10000 13000 Tuvault 7000 15 8050 68  Chapter 2    Using Single-Row Functions n As you can see in the example, using the COALESCE function helps you avoid writing several IF…THEN conditions You could write the same SQL using the CASE statement you learned about in Chapter as follows: SELECT last_name, salary, commission_pct AS comm, (CASE WHEN salary IS NULL THEN 900 WHEN commission_pct IS NOT NULL THEN salary+salary*commission_pct WHEN commission_pct IS NULL THEN salary+100 ELSE END) AS compensation FROM employees WHERE last_name like ‘T%’; LAST_NAME SALARY COMM COMPENSATION - -Taylor 8600 10320 Taylor 3200 3300 Tobias 900 Tucker 10000 13000 Tuvault 7000 15 8050 Try using WHEN salary IS NULL as the third condition in the CASE statement (instead of the first condition), and find out whether you see any difference in the result Using Single-Row Character Functions Single-row character functions operate on character data Most have one or more character arguments, and most return character values Character functions take the character input value and return a character or numeric value If the input to the function is a literal, be sure to enclose it in single quotes The exam focuses on many commonly used character functions such as SUBSTR, INSTR, and LENGTH When reading about these functions, pay particular attention to the commonly used functions Even experienced programmers get confused with the REPLACE and TRANSLATE functions In the following sections, I will review the single-row character functions in detail Character Function Overview Table 2.1 summarizes the single-row character functions I will cover each of these functions in the “Character Function Descriptions” section Using Single-Row Character Functions  69 Ta b l e    ​ Character Function Summary  ​ Function Description ASCII Returns the ASCII decimal equivalent of a character CHR Returns the character given the decimal equivalent CONCAT Concatenates two strings; same as the operator || INITCAP Returns the string with the first letter of each word in uppercase INSTR Finds the numeric starting position of a string within a string INSTRB Same as INSTR but counts bytes instead of characters LENGTH Returns the length of a string in characters LENGTHB Returns the length of a string in bytes LOWER Converts a string to all lowercase LPAD Left-fills a string to a set length using a specified character LTRIM Strips leading characters from a string REPLACE Performs substring search and replace RPAD Right-fills a string to a set length using a specified character RTRIM Strips trailing characters from a string SOUNDEX Returns a phonetic representation of a string SUBSTR Returns a section of the specified string, specified by numeric character positions SUBSTRB Returns a section of the specified string, specified by numeric byte positions TRANSLATE Performs character search and replace TRIM Strips leading, trailing, or both leading and trailing characters from a string UPPER Converts a string to all uppercase 70  Chapter 2    Using Single-Row Functions n The functions ASCII, INSTR, LENGTH, and REGEXP_INSTR return number values, though they take character datatype as the input Character Function Descriptions Over the years, Oracle has added several functions to its library to make the lives of developers easy so that they not have to write built-in functions Oracle has a function for most of the day-to-day programming needs Before you write your own custom-developed piece of code, it is always a good idea to scan the Oracle documentation on built-in functions The character functions in the following sections are arranged in alphabetical order, with descriptions and examples of each one ASCII ASCII(c1) takes a single argument, where c1 is a character string This function returns the ASCII decimal equivalent of the first character in c1 See also CHR() for the inverse operation SELECT ASCII(‘A’) Big_A, ASCII(‘z’) Little_Z, ASCII(‘AMER’) FROM dual; BIG_A LITTLE_Z ASCII(‘AMER’) 65 122 65 CHR CHR(i [ USING NCHAR_CS]) takes a single argument, where i is an integer This function returns the character equivalent of the decimal (binary) representation of the character If the optional USING NCHAR_CS is included, the character from the national character set is returned The default behavior is to return the character from the database character set SELECT CHR(65), CHR(122), CHR(223) FROM dual; CHAR65 CHAR122 CHAR233 - A z ß CONCAT CONCAT(c1,c2) takes two arguments, where c1 and c2 are both character strings This function returns c2 appended to c1 If c1 is NULL, then c2 is returned If c2 is NULL, then c1 is Using Single-Row Character Functions  71 returned If both c1 and c2 are NULL, then NULL is returned CONCAT returns the same results as using the concatenation operator: c1||c2 In the following example, notice the use of the nested function—a function inside a function—as an argument: SELECT CONCAT(CONCAT(first_name, ‘ ‘), last_name) employee_name, first_name || ‘ ‘ || last_name AS alternate_method FROM employees WHERE department_id = 30; EMPLOYEE_NAME Den Raphaely Alexander Khoo Shelli Baida Sigal Tobias Guy Himuro Karen Colmenares ALTERNATE_METHOD -Den Raphaely Alexander Khoo Shelli Baida Sigal Tobias Guy Himuro Karen Colmenares INITCAP INITCAP(c1) takes a single argument, where c1 is a character string This function returns c1 with the first character of each word in uppercase and all others in lowercase Words are delimited by white space or characters that are not alphanumeric SELECT data_value, INITCAP(data_value) initcap_example FROM sample_data; DATA_VALUE -THE three muskETeers ali and*41*thieves mississippi mister INDIA INITCAP_EXAMPLE -The Three Musketeers Ali And*41*Thieves Mississippi Mister India INSTR INSTR(c1,c2[,i[,j]]) takes four arguments, where c1 and c2 are character strings and i and j are integers This function returns the numeric character position in c1 where the j occurrence of c2 is found The search begins at the i character position in c1 INSTR returns a when the requested string is not found If i is negative, the search is performed backward, from right to left, but the position is still counted from left to right Both i and j default to 1, and j cannot be negative 72  Chapter 2    Using Single-Row Functions n The following example finds the first occurrence of i in the string starting from the fourth position of the string: SELECT data_value, INSTR(data_value,’i’,4,1) instr_example FROM sample_data; DATA_VALUE INSTR_EXAMPLE Comment - THE three muskETeers There is no “i” in the data value; so “0” ali and*41*thieves 14 The first “i” is skipped, since we start at the 4th position So the “i” in the 14th position is picked mississippi the first i in 2nd position is skipped mister INDIA INDIA has an “I” (upper case); so no match for “i” Here is another example using a negative argument for the beginning character position The search for the is string will start at the fourth position from the end and move to the left SELECT data_value, INSTR(data_value,’is’,-4,1) instr_example FROM sample_data; DATA_VALUE INSTR_EXAMPLE THE three muskETeers ali and*41*thieves mississippi mister INDIA INSTRB INSTRB(c1,c2[,i[,j]]) is the same as INSTR(), except it returns bytes instead of characters For single-byte character sets, INSTRB() is equivalent to INSTR() LENGTH LENGTH(c) takes a single argument, where c is a character string This function returns the numeric length in characters of c If c is NULL, a NULL is returned SELECT data_value, LENGTH(data_value) length_example FROM sample_data; Using Single-Row Character Functions  73 DATA_VALUE LENGTH_EXAMPLE -THE three muskETeers 20 ali and*41*thieves 18 mississippi 11 mister INDIA 12 LENGTHB LENGTHB(c) is the same as LENGTH(), except it returns bytes instead of characters For single-byte character sets, LENGTHB() is equivalent to LENGTH() LOWER LOWER(c) takes a single argument, where c is a character string This function returns the character string c with all characters in lowercase See also UPPER for the inverse operation SELECT data_value, LOWER(data_value) lower_example FROM sample_data; DATA_VALUE -THE three muskETeers ali and*41*thieves mississippi mister INDIA LOWER_EXAMPLE -the three musketeers ali and*41*thieves mississippi mister india LPAD LPAD(c1, i [,c2]) takes three arguments, where c1 and c2 are character strings and i is an integer This function returns the character string c1 expanded in length to i characters, using c2 to fill in space as needed on the left side of c1 If c1 is more than i characters, it is truncated to i characters c2 defaults to a single space See also RPAD The following example adds * to the SALARY column toward the left side Since it does not specify a fill-in character when LPAD is applied to last_name, Oracle uses the default space as the fill-in character SELECT LPAD(last_name,10) lpad_lname, LPAD(salary,8,’*’) lpad_salary FROM employees WHERE last_name like ‘J%’; 74  Chapter 2    Using Single-Row Functions LPAD_LNAME -Johnson Jones n LPAD_SAL -****6200 ****2800 LTRIM LTRIM(c1 [,c2]) takes two arguments, where c1 and c2 are character strings This function returns c1 without any leading characters that appear in c2 If no c2 characters are leading characters in c1 , then c1 is returned unchanged c2 defaults to a single space See also RTRIM and TRIM SELECT LTRIM(‘Mississippi’,’Mis’) ,LTRIM(‘Rpadded ‘) ,LTRIM(‘ Lpadded’) ,LTRIM(‘ Lpadded’, ‘Z’) FROM dual; test1 test2 test3 test4 TES TEST2 TEST3 TEST4 - - - -ppi Rpadded Lpadded Lpadded In the previous example, all occurrences of the trimmed characters M, i, and s are trimmed from the input string Mississippi, beginning on the left (with M) and continuing until the first character that is not an M, i, or s is encountered Note that the trailing i is not trimmed; only the leading characters are removed In TEST4, there is no occurrence of Z, so the input string is returned unchanged REPLACE REPLACE(c1, c2 [,c3]) takes three arguments, where c1 , c2, and c3 are character strings This function returns c1 with all occurrences of c2 replaced with c3 c3 defaults to NULL If c3 is NULL, all occurrences of c2 are removed If c2 is NULL, then c1 is returned unchanged If c1 is NULL, then NULL is returned SELECT REPLACE(‘uptown’,’up’,’down’) FROM dual; REPLACE( -downtown This function can come in handy when you need to some dynamic substitutions For example, suppose you have a number of indexes that were created in the _DATA tablespace instead of in the _INDX tablespace: Using Single-Row Character Functions  75 SELECT index_name, tablespace_name FROM user_indexes WHERE tablespace_name like ‘%DATA%’; INDEX_NAME -PK_DEPT PK_PO_MASTER TABLESPACE_NAME -HR_DATA PO_DATA You can generate the Data Definition Language (DDL) to rebuild these misplaced indexes in the correct location In this scenario, you know your tablespace naming convention has an INDX tablespace for every DATA tablespace You use the REPLACE function to generate the new tablespace name, replacing DATA with INDX So, the HR index is rebuilt in the HR_INDX tablespace, and the PO index is rebuilt in the PO_INDX tablespace SELECT ‘ALTER INDEX ‘||index_name|| ‘ rebuild tablespace ‘|| REPLACE(tablespace_name, ‘DATA’, ‘INDX’)|| ‘; ‘ DDL FROM user_indexes WHERE tablespace_name LIKE ‘%DATA%’; DDL ALTER INDEX PK_DEPT rebuild tablespace HR_INDX; ALTER INDEX PK_PO_MASTER rebuild tablespace PO_INDX; RPAD RPAD(c1, i [, c2]) takes three arguments, where c1 and c2 are character strings and i is an integer This function returns the character string c1 expanded in length to i characters, using c2 to fill in space as needed on the right side of c1 If c1 is more than i characters, it is truncated to i characters c2 defaults to a single space See also LPAD SELECT RPAD(first_name,15,’.’) rpad_fname, lpad(job_id,12,’.’) lpad_jid FROM employees WHERE first_name like ‘B%’; RPAD_FNAME Bruce Britney LPAD_JID - IT_PROG SH_CLERK 76  Chapter 2    Using Single-Row Functions n RTRIM RTRIM(c1 [,c2]) takes two arguments, where c1 and c2 are character strings This function returns c1 without any trailing characters that appear in c2 If no c2 characters are trailing characters in c1 , then c1 is returned unchanged c2 defaults to a single space See also LTRIM and TRIM SELECT RTRIM(‘Mississippi’,’ip’) ,RTRIM(‘Rpadded ‘) ,RTRIM(‘Rpadded ‘, ‘Z’) ,RTRIM(‘ Lpadded’) FROM dual; test1 test2 test3 test4 TEST1 TEST2 TEST3 TEST4 - - - -Mississ Rpadded Rpadded Lpadded SOUNDEX SOUNDEX(c1) takes a single argument, where c1 is a character string This function returns the Soundex phonetic representation of c1 The SOUNDEX function is usually used to locate names that sound alike The example returns the records with first names that sound like “Stevan.” SELECT first_name, last_name FROM employees WHERE SOUNDEX(first_name) = SOUNDEX(‘Stevan’); FIRST_NAME -Steven Steven Stephen LAST_NAME King Markle Stiles SUBSTR SUBSTR(c1, x [, y]) takes three arguments, where c1 is a character string and both x and y are integers This function returns the portion of c1 that is y characters long, beginning at position x If x is negative, the position is counted backward (that is, right to left) This function returns NULL if y is or negative y defaults to the remainder of string c1 SELECT SUBSTR(‘The Three Musketeers’,1,3) Part1 ,SUBSTR(‘The Three Musketeers’,5,5) Part2 Using Single-Row Character Functions  ,SUBSTR(‘The Three Musketeers’,11) ,SUBSTR(‘The Three Musketeers’,-5) FROM dual; Part3 Part4 PAR PART2 PART3 PART4 - - The Three Musketeers teers Parsing the Filename from the Whole Path Let’s look at a real example from the life of a DBA Suppose you want to extract only the filename from dba_data_files without the path name; you could use the following SQL Here the INSTR function is nested inside a SUBSTR function Single-row functions can be nested to any level When functions are nested, the innermost function is evaluated first The INSTR function is used to find the character position where the last \ appears in the filename string (looking for the first occurrence from the end) This position is passed into the SUBSTR function as the start position SELECT file_name, SUBSTR(file_name, INSTR(file_name,’\’, -1,1)+1) name FROM dba_data_files; FILE_NAME -C:\ORACLE\ORADATA\W11GR1\USERS01.DBF C:\ORACLE\ORADATA\W11GR1\UNDOTBS01.DBF C:\ORACLE\ORADATA\W11GR1\SYSAUX01.DBF C:\ORACLE\ORADATA\W11GR1\SYSTEM01.DBF C:\ORACLE\ORADATA\W11GR1\EXAMPLE01.DBF NAME USERS01.DBF UNDOTBS01.DBF SYSAUX01.DBF SYSTEM01.DBF EXAMPLE01.DBF To perform the same operation on Unix or Linux databases, replace \ in the INSTR function with / because / is used on Linux/Unix to separate directories Let’s review another example using the Linux or Unix platform Suppose you want to find out all the file systems (mount points) used by your database; you could use the following SQL: SELECT DISTINCT SUBSTR(file_name, 1, INSTR(file_name,’/’, 1,2)-1) fs_name FROM dba_data_files; 77 78  Chapter 2    Using Single-Row Functions n FS_NAME /u01 /u05 /ora_temp /ora_undo In this example, you started looking for the second occurrence of / using the INSTR function and used SUBSTR to extract only the characters from through the location before the second occurrence of / in the filename (hence the –1) SUBSTRB SUBSTRB(c1, i[, j]) takes three arguments, where c1 is a character string and both i and j are integers This function is the same as SUBSTR, except i and j are counted in bytes instead of characters For single-byte character sets, they are equivalent TRANSLATE TRANSLATE(c1, c2 ,c3) takes three arguments, where c1 , c2, and c3 are character strings This function returns c1 with all occurrences of characters in c2 replaced with the positionally corresponding characters in c3 A NULL is returned if any of c1, c2, or c3 is NULL If c3 has fewer characters than c2, the unmatched characters in c2 are removed from c1 If c2 has fewer characters than c3, the unmatched characters in c3 are ignored TRANSLATE is similar to the REPLACE function REPLACE substitutes a single string from another string, whereas TRANSLATE makes several single-character one-to-one substitutions The following example substitutes * for a, # for e, and $ for i, and it removes o and u from the last_name column: SELECT last_name, TRANSLATE(last_name, ‘aeiou’, ‘*#$’) no_vowel FROM employees WHERE last_name like ‘S%’; LAST_NAME Sarchand Sciarra Seo Smith Sullivan Sully NO_VOWEL -S*rch*nd Sc$*rr* S# Sm$th Sll$v*n Slly Using Single-Row Character Functions  79 Here is another example, where the case is reversed; uppercase letters are converted to lowercase, and lowercase letters are converted to uppercase: SELECT data_value, TRANSLATE(data_value, ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’, ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz’) FROM sample_data; DATA_VALUE -THE three muskETeers ali and*41*thieves mississippi mister INDIA TRANSLATE(DATA_VALUE -the THREE MUSKetEERS ALI AND*41*THIEVES MISSISSIPPI MISTER india TRIM TRIM([[c1] c2 FROM ] c3) can take three arguments, where c2 and c3 are character strings If present, c1 can be one of the following literals: LEADING, TRAILING, or BOTH This function returns c3 with all c1 (leading, trailing, or both) occurrences of characters in c2 removed A NULL is returned if any of c1 , c2, or c3 is NULL c1 defaults to BOTH c2 defaults to a space character c3 is the only mandatory argument If c2or c3 is NULL, the function returns a NULL It’s equivalent to applying both LTRIM and RTRIM on the string c3 SELECT TRIM(‘ fully padded ‘) test1 ,TRIM(‘ left padded’) test2 ,TRIM(‘right padded ‘) test3 FROM dual; TEST1 TEST2 TEST3 - -fully padded left padded right padded UPPER UPPER(c) takes a single argument, where c is a character string This function returns the character string c with all characters in uppercase UPPER frequently appears in WHERE clauses, when you’re not sure of the case of the data in the table See also LOWER SELECT first_name, last_name FROM employees WHERE UPPER(first_name) = ‘JOHN’; 80  Chapter 2    Using Single-Row Functions n FIRST_NAME LAST_NAME -John Chen SELECT data_value, UPPER(data_value) upper_data FROM sample_data; DATA_VALUE -THE three muskETeers ali and*41*thieves mississippi mister INDIA UPPER_DATA -THE THREE MUSKETEERS ALI AND*41*THIEVES MISSISSIPPI MISTER INDIA Using Single-Row Numeric Functions When you think of numeric functions, the tasks that come to mind are finding a total, finding the average, counting the number of records, and so on These numeric functions are group functions that operate on one or more rows I’ll discuss group functions in Chapter 3, “Using Group Functions.” In the following sections, I will review the numeric functions used on single rows Single-row numeric functions operate on numeric data and perform some kind of mathematical or arithmetic manipulation When using a literal in a numeric function, not enclose it in single quotes Literals in single quotes are treated as a character datatype Numeric Function Overview Table 2.2 summarizes the single-row numeric functions in Oracle 11g I will cover each of these functions in the “Numeric Function Descriptions” section Ta b l e    ​ Numeric Function Summary  ​ Function Description ABS Returns the absolute value ACOS Returns the arc cosine ASIN Returns the arc sine ATAN Returns the arc tangent ... -C: \ORACLE\ ORADATA\W11GR1\USERS01.DBF C: \ORACLE\ ORADATA\W11GR1\UNDOTBS01.DBF C: \ORACLE\ ORADATA\W11GR1\SYSAUX01.DBF C: \ORACLE\ ORADATA\W11GR1\SYSTEM01.DBF C: \ORACLE\ ORADATA\W11GR1\EXAMPLE01.DBF... 118 6246 ORACLE. EXE (W000) BTHOMAS 121 963 sqlplus.exe DBSNMP 124 23310 emagent.exe DBSNMP 148 608 emagent.exe 150 ORACLE. EXE (FBDA) 152 ORACLE. EXE (SMCO) 155 ORACLE. EXE (MMNL) 156 ORACLE. EXE... 158 ORACLE. EXE (MMON) 159 ORACLE. EXE (RECO) 164 ORACLE. EXE (MMAN) … … … (Output truncated) As you can see, the background processes not have usernames To find out only the user sessions in the database,

Ngày đăng: 07/11/2013, 11:15

TỪ KHÓA LIÊN QUAN