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
633,44 KB
Nội dung
Using Other Single-Row Functions 131 Parameter Description BG_JOB_ID Returns the job ID (that is, DBA_JOBS ) if the session was created by a background process. Returns NULL if the session is a fore- ground session. See also FG_JOB_ID . CLIENT_IDENTIFIER Returns the client session identifier in the global context. It can be set with the DBMS_SESSION built-in package. CLIENT_INFO Returns the 64 bytes of user session information stored by DBMS_APPLICATION_INFO . CURRENT_BIND Returns bind variables for fine-grained auditing. CURRENT_SCHEMA Returns the current schema as set by ALTER SESSION SET CURRENT_SCHEMA or, by default, the login schema/ID. CURRENT_SCHEMAID Returns the numeric ID for CURRENT_SCHEMA . CURRENT_SQL Returns the SQL that triggered fine-grained auditing (use only within scope inside the event handler for fine-grained auditing). CURRENT_SQL_LENGTH Returns the length of the current SQL that triggered fine- grained auditing. DB_DOMAIN Returns the contents of the DB_DOMAIN init.ora parameter. DB_NAME Returns the contents of the DB_NAME init.ora parameter. DB_UNIQUE_NAME Returns the contents of the DB_UNIQUE_NAME init.ora parameter. ENTRYID Returns the auditing entry identifier ENTERPRISE_IDENTITY Returns OID DN for enterprise users, for local users NULL. FG_JOB_ID Returns the job ID of the current session if a foreground pro- cess created it. Returns NULL if the session is a background session. See also BG_JOB_ID . GLOBAL_CONTEXT_MEMORY Returns the number in the SGA by the globally accessible context. GLOBAL_UID Returns the global user ID from OID. HOST Returns the hostname of the machine from where the client connected. This is not the same terminal in V$SESSION . table 2.14 Parameters in the USERENV Namespace (continued) 95127c02.indd 131 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 132 Chapter 2 N Using Single-Row Functions Parameter Description IDENTIFICATION_TYPE Returns how the user is set to authenticate in the database: LOCAL , EXTERNAL , or GLOBAL. INSTANCE Returns the instance number for the instance to which the session is connected. This is always 1 unless you are running Oracle Real Application Clusters. INSTANCE_NAME Returns the name of the instance. IP_ADDRESS Returns the IP address of the machine from where the client connected. ISDBA Returns TRUE if the user connected AS SYSDBA . LANG Returns the ISO abbreviation for the language name. LANGUAGE Returns a character string containing the language and terri- tory used by the session and the database character set in the form language_territory.characterset. MODULE Returns the application name set through DBMS_APPLICATION_INFO . NETWORK_PROTOCOL Returns the network protocol being used as specified in the PROTOCOL= section of the connect string or tnsnames.ora definition. NLS_CALENDAR Returns the calendar for the current session. NLS_CURRENCY Returns the currency for the current session. NLS_DATE_FORMAT Returns the date format for the current session. NLS_DATE_LANGUAGE Returns the language used for displaying dates. NLS_SORT Returns the binary or linguistic sort basis. NLS_TERRITORY Returns the territory for the current session. OS_USER Returns the operating-system username for the current session. POLICY_INVOKER Returns the invoker of row-level security-policy functions. PROXY_ENTERPRISE_ IDENTITY Returns OID DN when the proxy user is an enterprise user. table 2.14 Parameters in the USERENV Namespace (continued) 95127c02.indd 132 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Other Single-Row Functions 133 Parameter Description PROXY_GOLBAL_UID Returns the global user ID from OID for Enterprise User Secu- rity proxy users. PROXY_USER Returns the name of the database user who opened the current session for the session user. PROXY_USERID Returns the numeric ID for the database user who opened the current session for the session user. SERVER_HOST Returns the hostname of the machine where the instance is running. SERVICE_NAME Returns the name of the service where the session is connected. SESSION_USER Returns the database username for the current session. SESSION_USERID Returns the numeric database user ID for the current session. SESSIONID Returns the auditing session identifier AUDSID. This parameter is out of scope for distributed queries. SID Returns the session number (same as the SID from V$SESSION ). STATEMENT_ID Returns the auditing statement identifier. TERMINAL Returns the terminal identifier for the current session. This is the same as the terminal in V$SESSION . Here are few more examples of SYS_CONTEXT in the USERENV namespace: SELECT SYS_CONTEXT(‘USERENV’, ‘OS_USER’), SYS_CONTEXT(‘USERENV’, ‘CURRENT_SCHEMA’), SYS_CONTEXT(‘USERENV’, ‘HOST’), SYS_CONTEXT(‘USERENV’, ‘NLS_TERRITORY’) FROM dual; SYS_CONTEXT(‘USERENV’,’OS_USER’) SYS_CONTEXT(‘USERENV’,’CURRENT_SCHEMA’) SYS_CONTEXT(‘USERENV’,’HOST’) SYS_CONTEXT(‘USERENV’,’NLS_TERRITORY’) -------------------------------------------- table 2.14 Parameters in the USERENV Namespace (continued) 95127c02.indd 133 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 134 Chapter 2 N Using Single-Row Functions oracle HR linux04.mycompany.corp AMERICA SYS_GUID SYS_GUID() generates a globally unique identifier as a RAW value. This function is useful for creating a unique identifier to identify a row. SYS_GUID() returns a 32-bit hexadecimal representation of the 16-byte RAW value. SELECT SYS_GUID() FROM DUAL; SYS_GUID() -------------------------------- CDA78A020D6E43A6AB743A5CE8CB8C55 SELECT SYS_GUID() FROM DUAL; SYS_GUID() -------------------------------- DC7C19A3AD264CE184C64194E65F83E5 UID UID takes no parameters and returns the integer user ID for the current user connected to the session. The user ID uniquely identifies each user in a database and can be selected from the DBA_USERS view. SQL> SHOW USER USER is “BTHOMAS” SELECT username, account_status FROM dba_users WHERE user_id = UID; USERNAME ACCOUNT_STATUS ---------------- --------------- BTHOMAS OPEN 95127c02.indd 134 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Other Single-Row Functions 135 USER USER takes no parameters and returns a character string containing the username for the current user. SELECT default_tablespace, temporary_tablespace FROM dba_users WHERE username = USER; DEFAULT_TABLESPACE TEMPORARY_TABLESPACE ------------------------------ --------------------- USERS TEMP USERENV USERENV ( opt ) takes a single argument, where opt is one of the following options: ISDBA ÛN returns TRUE if the SYSDBA role is enabled in the current session. SESSIONID ÛN returns the AUDSID auditing session identifier. ENTRYID ÛN returns the auditing entry identifier if auditing is enabled for the instance (the init.ora parameter AUDIT_TRAIL is set to TRUE ). INSTANCE ÛN returns the instance identifier to which the session is connected. This option is useful only if you are running the Oracle Parallel Server and have multiple instances. LANGUAGE ÛN returns the language, territory, and database character set. The delimiters are an underscore ( _ ) between language and territory and a period ( . ) between the terri- tory and character set. LANG ÛN returns the ISO abbreviation of the session’s language. TERMINAL ÛN returns a VARCHAR2 string containing information corresponding to the operating system identifier for the current session’s terminal. The option can appear in uppercase, lowercase, or mixed case. The USERENV function has been deprecated since Oracle 9i. It is recommended to use the SYS_CONTEXT function with the built-in USERENV namespace instead. VSIZE VSIZE(x) takes a single argument, where x is an expression. This function returns the size in bytes of the internal representation of the x . SELECT last_name, first_name, VSIZE(last_name) ln_size, VSIZE(first_name) fn_size FROM employees WHERE last_name like ‘K%’; 95127c02.indd 135 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 136 LAST_NAME FIRST_NAME LN_SIZE FN_SIZE ------------ -------------------- ---------- ---------- Kaufling Payam 8 5 Khoo Alexander 4 9 King Janette 4 7 King Steven 4 6 Kochhar Neena 7 5 Kumar Sundita 5 7 Since the database character set is single-byte, the byte used for each character is 1 ; hence, the size shown here is actually the number of characters in the input. For multibyte characters, this would be different. Summary This chapter introduced single-row functions. It started by discussing the functions avail- able in Oracle11g to handle NULL s. Then it discussed the single-row functions available in Oracle11g by grouping them into character, numeric, date, and conversion functions. You learned that single-row functions return a value for each row as it is retrieved from the table. You can use single-row functions to interpret NULL values, format output, convert datatypes, transform data, perform date arithmetic, give environment information, and perform trigonometric calculations. You can use single-row functions in the SELECT , WHERE , and ORDER BY clauses of SELECT statements. I covered the rich assortment of functions available in each datatype category and some functions that work on any datatype. The NVL , NVL2 , and COALESCE functions interpret NULL values. The single-row character functions operate on character input. The INSTR function returns the position of a substring within the string. The SUBSTR function returns a portion of the string. INSTR and SUBSTR are great for extracting part of the input string. REPLACE and TRANSLATE transform the input. Single-row numeric functions operate on numeric input. FLOOR , CEIL , ROUND , and TRUNC get the nearest number. FLOOR , CEIL , and ROUND return the nearest integer, whereas ROUND returns a value rounded to certain digits of precision. REMAINDER and MOD are similar functions. Date functions operate on datetime values. SYSDATE and SYSTIMESTAMP values return the current date and time. MONTHS_BETWEEN finds the number of months between two date val- ues. ADD_MONTHS is a commonly used function and can add months to or subtract months from a date. You can use ROUND and TRUNC on datetime values to find the nearest date, month, or year. Of the conversion functions, TO_CHAR and TO_DATE are the most commonly used. I also reviewed the format codes that can be used with numeric and datetime values. The DECODE function evaluates a condition, and you can easily build IF…THEN…ELSE logic into SQL using the DECODE function. 95127c02.indd 136 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 137 Exam Essentials Understand where single-row functions can be used. Single-row functions can be used in the SELECT , WHERE , and ORDER BY clauses of SELECT statements. Know the effects that NULL values can have on arithmetic and other functions. Any arith- metic operation on a NULL results in a NULL . This is true of most functions as well. Use the NVL , NVL2 , and COALESCE functions to deal with NULL s. Review the character-manipulation functions. Understand the arguments and the result of using character-manipulation functions such as INSTR , SUBSTR , REPLACE , and TRANSLATE . Understand the numeric functions. Know the effects of using TRUNC and ROUND with -n as the second argument. Also practice using LENGTH and INSTR , which return a numeric result, inside SUBSTR and other character functions. Know how date arithmetic works. When adding or subtracting numeric values from a DATE datatype, whole numbers represent days. Also, the date/time intervals INTERVAL YEAR TO MONTH and INTERVAL DAY TO SECOND can be added or subtracted from date/time datatypes. You need to know how to interpret and create expressions that add intervals to or subtract intervals from dates. Know the datatypes for the various date/time functions. Oracle has many date/time func- tions to support the date/time datatypes. You need to know the return datatypes for these functions. SYSDATE and CURRENT_DATE return a DATE datatype. CURRENT_TIMESTAMP and SYSTIMESTAMP return a TIMESTAMP WITH TIME ZONE datatype. LOCALTIMESTAMP returns a TIMESTAMP datatype. Know the format models for converting dates to/from character strings. In practice, you can simply look up format codes in a reference. For the certification exam, you must have them memorized. Understand the use of the DECODE function. DECODE acts like a case statement in C, Pascal, or Ada. Learn how this function works and how to use it. 95127c02.indd 137 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 138 Review Questions Review Questions 1. You want to display each project’s start date as the day, week, number, and year. Which statement will give output like the following? Tuesday Week 23, 2008 A. SELECT proj_id, TO_CHAR(start_date, ‘DOW Week WOY YYYY’) FROM projects; B. SELECT proj_id, TO_CHAR(start_date,’Day’||’ Week’||’ WOY, YYYY’) FROM projects; C. SELECT proj_id, TO_CHAR(start_date, ‘Day” Week” WW, YYYY’) FROM projects; D. SELECT proj_id, TO_CHAR(start_date, ‘Day Week# , YYYY’) FROM projects; E. You can’t calculate week numbers with Oracle. 2. What will the following statement return? SELECT last_name, first_name, start_date FROM employees WHERE hire_date < TRUNC(SYSDATE) – 5; A. Employees hired within the past five hours B. Employees hired within the past five days C. Employees hired more than five hours ago D. Employees hired more than five days ago 3. Which assertion about the following statements is most true? SELECT name, region_code||phone_number FROM customers; SELECT name, CONCAT(region_code,phone_number) FROM customers; A. If REGION_CODE is NULL, the first statement will not include that customer’s PHONE_ NUMBER. B. If REGION_CODE is NULL, the second statement will not include that customer’s PHONE_ NUMBER. C. Both statements will return the same data. D. The second statement will raise an error if REGION_CODE is NULL for any customer. 4. Which single-row function could you use to return a specific portion of a character string? A. INSTR B. SUBSTR C. LPAD D. LEAST 95127c02.indd 138 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Review Questions 139 5. The data in the PRODUCT table is as described here. The bonus amount is calculated as the lesser of 5 percent of the base price or 20 percent of the surcharge. sku name division base_price surcharge 1001 PROD-1001 A 200 50 1002 PROD-1002 C 250 1003 PROD-1003 C 240 20 1004 PROD-1004 A 320 1005 PROD-1005 C 225 40 Which of the following statements will achieve the desired results? A. SELECT sku, name, LEAST(base_price * 1.05, surcharge * 1.2) FROM products; B. SELECT sku, name, LEAST(NVL(base_price,0) * 1.05, surcharge * 1.2) FROM products; C. SELECT sku, name, COALESCE(LEAST(base_price*1.05, surcharge * 1.2), base_price * 1.05) FROM products; D. A, B, and C will all achieve the desired results. E. None of these statements will achieve the desired results. 6. Which function(s) accept arguments of any datatype? (Choose all that apply.) A. SUBSTR B. NVL C. ROUND D. DECODE E. SIGN 7. What will be returned by SIGN(ABS(NVL(-32,0)))? A. 1 B. 32 C. –1 D. 0 E. NULL 95127c02.indd 139 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 140 Review Questions 8. The SALARY table has the following data: LAST_NAME FIRST_NAME SALARY ------------ -------------------- ---------- Mavris Susan 6500 Higgins Shelley 12000 Tobias Sigal Colmenares Karen 2500 Weiss Matthew 8000 Mourgos Kevin 5800 Rogers Michael 2900 Stiles Stephen 3200 Consider the following SQL, and choose the best option: SELECT last_name, NVL2(salary, salary, 0) N1, NVL(salary,0) N2 FROM salary; A. Column N1 and N2 will have different results. B. Column N1 will show zero for all rows, and column N2 will show the correct salary values, and zero for Tobias. C. The SQL will error out because the number of arguments in the NVL2 function is incorrect. D. Columns N1 and N2 will show the same result. 9. Which two functions could you use to strip leading characters from a character string? (Choose two.) A. LTRIM B. SUBSTR C. RTRIM D. INSTR E. STRIP 10. What is the result of MOD(x1, 4), if x1 is 11? A. –1 B. 3 C. 1 D. REMAINDER(11,4) 95127c02.indd 140 2/18/09 6:46:45 AM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... date value from the two statements will be different D Both statements will generate an error 16 What will the following SQL statement return? SELECT COALESCE(NULL, Oracle ‘, Certified ) FROM dual; A NULL B Oracle C Certified D Oracle Certified 17 Which expression will always return the date one year later than the current date? A SYSDATE + 365 B SYSDATE + TO_YMINTERVAL(‘01-00’) C CURRENT_DATE + 1... space usage in a database The DBA_SEGMENTS dictionary view shows the segments allocated in the database each table or index created in the database must have at least one segment created The columns you are interested in for the query are tablespace_name, owner (or the schema name), and bytes (allocated space in bytes) The first SQL just gives the total space used by all the objects in the database This... STDDEV Returns the standard deviation SUM Adds all values and returns the result VARIANCE Returns the sample variance, or 1 for sample size 1 Table 3.2 summarizes the group functions available in Oracle Database11g that are not included in Table 3.1 Although they are less likely to appear on the certification exam, they are still important to review Utilizing Aggregate Functions 155 Ta b l e 3 2... The REPLACE function performs search-and-replace string operations There is no IFELSE function The DECODE function is the one that implements IF…THEN…ELSE logic Chapter 3 Using Group Functions Oracle Database 11g: SQL Fundamentals I exam objectives covered in this chapter: ÛÛ Reporting Aggregated Data Using the Group Functions NN Identify the available group functions NN Describe the use of group functions... SUM_UQ -9 7 60000 47900 Unlike with single-row functions, you cannot use programmer-written functions on grouped data Utilizing Aggregate Functions As with single-row functions, Oracle offers a rich variety of aggregate functions These functions can appear in the SELECT, ORDER BY, or HAVING clauses of SELECT statements When used in the SELECT clause, they usually require a GROUP... certification-exam question that tests whether you will incorrectly put a group function in the WHERE clause Grouping Data with GROUP BY As the name implies, group functions work on data that is grouped You tell the database how to group or categorize the data with a GROUP BY clause Whenever you use a group function in the SELECT clause of a SELECT statement, you must place all nongrouping/nonconstant columns in the... “#Employees” FROM employees; SELECT department_id, COUNT(*) “#Employees” * ERROR at line 1: ORA-00937: not a single-group group function Since you used an aggregate function and nonaggregated column, Oracle gave an error and is telling you to group the data Here you have to use the GROUP BY clause If you include Utilizing Aggregate Functions 151 a group function in the SELECT clause, you cannot select... department_id; Utilizing Aggregate Functions 153 AVERAGE_SALARY -8600 4420 7000 9500 10000 19333.3333 10150 3475.55556 6500 8955.88235 4400 5760 If you have more than one column in the GROUP BY clause, Oracle creates groups within groups The order of columns in the GROUP BY clause determines the grouping Multiple columns in the GROUP BY clause are required when you have more than one nonaggregate column... PR_REP 1 SA_MAN 5 SA_REP 29 154 Chapter 3 Using Group Functions n 90 90 100 100 110 110 AD_PRES AD_VP FI_ACCOUNT FI_MGR AC_ACCOUNT AC_MGR SA_REP 1 2 5 1 1 1 1 The GROUP BY clause groups data, but Oracle does not guarantee the order of the result set by the grouping order To order the data in any specific order, you must use the ORDER BY clause Group-Function Overview Tables 3.1 and 3.2 summarize... specified The YY format will use the current century, and the YYYY format expects the century in the input 16 B The COALESCE function returns the first non-NULL parameter, which is the character string Oracle ‘ 17 E Option A will not work if there is a February 29 (leap year) in the next 365 days Option B will always add one year to the present date, except if the current date is February 29 (leap year) . statement return? SELECT COALESCE(NULL, Oracle ‘, Certified ) FROM dual; A. NULL B. Oracle C. Certified D. Oracle Certified 17. Which expression will always. the functions avail- able in Oracle 11g to handle NULL s. Then it discussed the single-row functions available in Oracle 11g by grouping them into character,