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

Tài liệu Oracle SQL Jumpstart with Examples- P5 docx

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

Tiêu đề Using iSQL*Plus
Thể loại Tài liệu
Định dạng
Số trang 50
Dung lượng 1,69 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Single-Row Functions In this chapter: What types of built-in functions are available?. 176 9.2 Single-Row Functions9.1 Types of Functions Oracle divides all functions into the following

Trang 2

8.4 Using iSQL*Plus 171

This example placed the username, password, and Oracle database work name (SID) in the source code This is not necessarily a good idea in acommercial environment from a security perspective Anyone can view thesource code of an HTML document and retrieve information It would bebetter to modify the HTML in your document so that the user is required

net-to enter a username and password Additionally, secure socket layers (SSL)can be used to encrypt data traveling between a Web browser and the server

8.4.2 iSQL*Plus versus SQL*Plus

The main features of iSQL*Plus are similar to the features of SQL*Plus orSQL*Plus Worksheet:

 Enter SQL commands in a box and click the Execute button to play the results Results can be displayed below the box or in a newbrowser window

dis- Adjust environment settings by clicking the Preferences button, using

a series of radio buttons and boxes to modify settings such as ING, RECSEP, and so on

HEAD- Use variables just like SQL*Plus, except you cannot use the ACCEPT

or PROMPT commands to prompt for values iSQL*Plus displays itsown prompt

Note: iSQL*Plus allows prompts for input values

 Review and retrieve previous SQL commands by clicking the Historybutton, much like SQL*Plus Worksheet

Trang 3

172 8.4 Using iSQL*Plus

 The port number should also be in the SETUPINFO.TXT file in thedirectory $ORACLE_HOME/Apache/Apache This file should con-tain entries such as the following:

http://<hostname>:7778 http://<hostname>:4443

Note: Replace hostname as appropriate.

 The file called ORACLE_APACHE.CONF in the

$ORACLE_HOME/Apache/Apache/conf directory must includethe file ISQLPLUS.CONF in the ORACLE_HOME/sqlplus/admindirectory The include command should be of the following form Besure there are no comments (#) in unexpected places

include "$ORACLE_HOME/sqlplus/admin/isqlplus.conf"

 Try stopping and restarting the HTTP Server, especially if you havemade any changes to any configuration files A bug in Oracle 9.2 forWindows 2000 caused errors when starting and stopping the HTTPServer using both the Windows service and the Apache command onthe Start menu A solution to this issue is to set the service to Manualand always start and stop Apache and the HTTP Server with the fol-lowing commands executed in a DOS shell (the command line):

C:\oracle\ora92\Apache\Apache\apache -k start C:\oracle\ora92\Apache\Apache\apache - k shutdown

8.4.4 Customizing iSQL*Plus Display

Numerous preferences can be changed from the iSQL*Plus interface on theclient machine Additionally, on the server there is an HTML cascadingstyle sheet.1 This style sheet can be altered to change output appearance.The HTML cascading style sheet is called IPLUS.CSS and is located in the

$ORACLE_HOME/sqlplus/admin/iplus directory on the server Changingthe style sheet allows customization of colors and fonts used by iSQL*Pluswhen it formats output for queries Using the same simple query used pre-

Trang 4

 The TH or HTML table heading tag or element is changed wherehighlighted.

TH { font : bold 10pt Arial, Helvetica, sans-serif;

Figure 8.29

Changing the iSQL*Plus Style

Sheet on the Server.

Trang 5

This chapter has covered more detail on SQL*Plus and related tools, inaddition to the introductory information provided in Chapter 1 The nextchapter moves back into Oracle SQL and looks at functions, namely single-row functions.

8.5 Endnotes

1 www.oracledbaexpert.com/menu/DHTML.html

Trang 6

Single-Row Functions

In this chapter:

 What types of built-in functions are available?

 What are single-row functions?

 What are the categories of single-row functions?

 How do functions work with queries?

 What are the options when formatting strings, numbers, and dates?

 What are data conversion functions?

 How are functions combined?

This chapter uses the queries you have worked with in previous chaptersand expands the way you can use columns by introducing functions Youwill examine the types of functions used for different data types Finally,you will experiment with combining functions together for more flexibility

A function is a built-in PL/SQL program that always returns a singlevalue You can use the predefined functions (such as the ones discussed inthis chapter) or you can create your own (see Chapter 24) A functionalways returns a single value, as opposed to a procedure, which is a similartype of program but is able to return more than one value You can call afunction within a query or other SQL command You have already seen afew functions in previous chapters (e.g., NVL and SYSDATE) Before weexamine single-row functions in detail, let’s look at Oracle-provided built-

in functions in general Grouping functions are covered in Chapter 11, ular expression functions in Chapter 14, object reference functions inChapter 16, and XML functions in Chapter 17

reg-Chap9.fm Page 175 Thursday, July 29, 2004 10:06 PM

Trang 7

176 9.2 Single-Row Functions

9.1 Types of Functions

Oracle divides all functions into the following categories:

 Single-Row Functions Functions that operate on a single row at atime This chapter examines this type of function For example, theUPPER() function converts characters to uppercase

 Grouping Functions Chapter 11 covers grouping functions indetail

 Aggregate Functions Functions that operate on a group of rows

at one time and return a single row For example, the COUNT()function counts the number of rows in a table

 Analytical Functions Functions that operate on groups of rowsand return one or more summary rows For example, the STD-DEV() OVER() function returns the standard deviation rowsbased on values in one or more columns

 Object Reference Functions.Functions that manipulate the value incolumns with the REF datatype in object tables For example, theDEREF() function returns the value of an attribute in the referencedobject table (see Chapter 16)

 User-Defined Functions Functions that are built by you and form whatever data manipulations you program them to do Exam-ples of user-defined functions are given throughout this book, withsyntactical details in Chapter 24

per-This chapter covers many of the dozens of single-row functions availablefor your use in queries

9.2 Single-Row Functions

Single-row functions add a great deal of power to queries Use functions inthe SELECT clause to modify the appearance of dates, for example Addfunctions to the WHERE clause to help determine which rows to include inquery results Place functions in the ORDER BY clause to fine-tune sorting

Chap9.fm Page 176 Thursday, July 29, 2004 10:06 PM

Trang 8

 Character or String Functions Functions that require a charactervalue or string as input (see Figure 9.1).

 Number Functions Functions that require a number as input.Most of these return a number For example, the SIGN functionreturns -1 if the number is negative, 0 if it is zero, and 1 if it is posi-tive (see Figure 9.2)

 Binary Floating-Point Number Functions These tions are new to Oracle Database 10g and could possibly beviewed as a subset of number functions, except that they operatespecifically on binary floating-point numbers (see Figure 9.2)

func- Datetime Functions Functions that require a date value as input(see Figure 9.3)

 Conversion Functions Functions that convert one datatype toanother For example, the TO_CHAR function can convert a date ornumber to a character value (see Figure 9.4)

 Miscellaneous Functions Functions that perform unusual tasks Forexample, the DECODE function acts like an IF-THEN-ELSE con-struct or CASE statement (see Figure 9.5)

Figures 9.1 through 9.5 show all the different types of single-row tions Functions highlighted and marked with an asterisk (*INITCAP) ineach figure are discussed in this chapter Additionally, many functions arereferred to in other chapters

Chap9.fm Page 177 Thursday, July 29, 2004 10:06 PM

Trang 9

Chap9.fm Page 178 Thursday, July 29, 2004 10:06 PM

Trang 10

9.2 Single-Row Functions 179

Figure 9.4

Single-Row Conversion Functions.

Figure 9.5

Single-Row Miscellaneous Functions.

Chap9.fm Page 179 Thursday, July 29, 2004 10:06 PM

Trang 11

180 9.2 Single-Row Functions

The next sections define all of the functions highlighted in Figures 9.1and 9.2, divided by their categories Functions detailed in this chapter aregenerally the more useful functions As already stated, the remaining func-tions tend to be obscure and seldom used In fact, some functions included

in this chapter are obscure Let’s begin with string functions

9.2.1 String Functions

The string functions manipulate alphanumeric data In this section, aftereach function is defined, an example shows how the function is used andwhat it returns

 CONCAT(expression, expression) Concatenation of strings is theadding together of two strings This function performs the same task

as the string concatenation operator || (see Chapter 7)

CONCAT('Oracle',' Database 10g') = 'Oracle Database 10g' 'Oracle'||' Database '||'10g' = 'Oracle Database 10g' 'My name is '||FIRST_NAME = 'My name is Jim'

 LOWER(expression), UPPER(expression), and sion) LOWER converts to lowercase, UPPER to uppercase, andINITCAP to mixed case (first letter of each word in uppercase)

INITCAP(expres-INITCAP('oracle certified professional')

= 'Oracle Certified Professional'

 INSTR(expression, substring [, position [, occurrence]]) Returnsthe position of a substring within a string (the first character in thestring is at position 1) The position and occurrence parameters areoptional The position parameter determines a start point to searchfrom, and occurrence indicates which duplicate, if any, of the sub-string should be matched In the following example, the secondoccurrence of the string 10g begins at position 19:

INSTR('oracle 10g oracle 10g oracle 10g','10g',1,2) = 19

 LENGTH(expression) The length in characters of a string

LENGTH('oracle certified professional') = 29 LENGTH(LAST_NAME) = length of the data in the column

 LPAD(expression, n [, expression]) and RPAD(expression, n [, expression]) Left or right pad a string from the left or the right (start

or end of the string) with the specified characters in the second string,

up to a string length of n characters

Chap9.fm Page 180 Thursday, July 29, 2004 10:06 PM

Trang 12

9.2 Single-Row Functions 181

LPAD('oracle',10,'X') = 'XXXXoracle' RPAD('oracle',10,'X') = 'oracleXXXX'

Note: Padding a string is sometimes referred to as filling a string

 TRIM([[LEADING|TRAILING|BOTH] character FROM]

expression), LTRIM(expression, string-set), and sion, string-set) LTRIM and RTRIM will remove from the left andthe right of the string, respectively, any characters contained withinthe string set, until a character not in the string set is found TheLTRIM and RTRIM functions are less useful than the TRIM func-tion TRIM will remove characters from the string from the left, theright, or both In its simplest form, TRIM can be used to removeleading and trailing spaces from a string

RTRIM(expres-TRIM(' oracle ') = 'oracle'Remember that spaces embedded between other characters do notget removed, until a character not in the string set is found As aresult, for the next example there is no change

TRIM(' o r a c l e ') = 'o r a c l e' TRIM( LEADING '-' FROM ' -608-444-3029') = '608-444-3029'

 REPLACE(expression, search [, replace]) and LATE(expression, search [, replace]) REPLACE will replace everyoccurrence of the search string with the replacement string Wherethe REPLACE function matches any search string within the string,TRANSLATE will match each character between the search andreplace strings by the position of characters in both the search andreplace strings Phew! In simple terms, REPLACE replaces groups ofcharacters and TRANSLATE translates individual characters

TRANS-REPLACE(' o r a c l e',' ','') = 'oracle' REPLACE('My dog has fleas.','as','odd') = 'My dog hodd fleodd.'

In the first TRANSLATE function example following, nothing ischanged because the space in the search string has no correspondingvalue in the replace string

TRANSLATE(' o r a c l e ','oracle ','12345X') = '12345X'

TRANSLATE('My dog has fleas.','agf','AGF') = 'My doG hAs FleAs.'

Chap9.fm Page 181 Thursday, July 29, 2004 10:06 PM

Trang 13

182 9.2 Single-Row Functions

 SUBSTR(expression, [-]position[, length]) The SUBSTR tion returns a portion of a string If the length parameter is omitted,then all characters after the value of position are returned If the posi-tion parameter is positive, then the substring value is extracted fromthe left of the string; otherwise, if the parameter is negative, the value

func-is extracted from the right (end) of the string

SUBSTR('oracle certified professional', 8,9) = 'certified'

SUBSTR('oracle certified professional',-12,12) = 'professional'

Here is a quick example using some of the string functions tioned previously Figure 9.6 shows the results The query shows thecomplete value of the NAME column, followed by the length of thevalue, a section of the name, and finally, the position of the secondoccurrence of the letter “a” in the name Notice that the INSTR func-tion returns zero if it cannot find a match

men-SELECT NAME, LENGTH(NAME) "Length"

, SUBSTR(NAME,5,5) "Letters 5 thru 9"

, INSTR(NAME,'a',1,2) "Second a"

 ABS(n) Finds an absolute value of a number An absolute value

function returns the positive or unsigned value of a negative or tive number

posi-ABS(-125) = 125 ABS(125) = 125

 CEIL(n) and FLOOR(n) Ceiling and floor are similar to rounding

and truncating functions Ceiling returns the next integer greater

than n Floor returns the next integer less than n

CEIL(1.1) = 2 Chap9.fm Page 182 Thursday, July 29, 2004 10:06 PM

Trang 14

9.2 Single-Row Functions 183

FLOOR(1.9) = 1

 MOD(m, n) MOD is the modulus or remainder function, which

returns the remainder of the first value divided by the second value (m divided by n) The first value is returned if the second value is zero

MOD(5,2) = 1 MOD(4,0) = 4 MOD(9,3) = 0 MOD(23,4) = 3

 POWER(m, n) The exponential function raises m to the power of n

(the nth power).

POWER(2,3) = 8 (23 = 2 * 2 * 2 = 4 * 2 = 8)

 ROUND(n [, places]) ROUND is a proper mathematical rounding

function as opposed to the CEIL and FLOOR functions For theROUND function, a decimal 5 and over will be rounded up andbelow 5 will be rounded down The third example following isrounded to two decimal places and the fourth to three decimal places

Figure 9.6

Some String Functions.

Trang 15

184 9.2 Single-Row Functions

ROUND(1.4) = 1 ROUND(1.5) = 2 ROUND(1.42356,2) = 1.42 ROUND(1.42356,3) = 1.424 ROUND(18755.24,-2) = 18800

 SIGN(n) Returns –1 if negative, 0 if 0, and 1 if positive.

SIGN(-5032) = –1 SIGN(0) = 0 SIGN(5000) = 1

 SQRT(n) Calculates the square root of a number.

SQRT(4) = 2 (2 * 2 = 4)

 TRUNC(n [, places]) TRUNC is a truncate function A truncate

function always rounds down by removing trailing numerals from anumber, effectively rounding down regardless of the 5 cutoff value.TRUNC can also truncate both sides of the decimal point

TRUNC(147.65,1) = 147.6 TRUNC(147.65,-2) = 100

 Other Mathematical Functions The following functions perform

obscure mathematical or trigonometric calculations These types offunctions are rarely used other than in financial or numericallyrelated applications Some of these functions are listed here There aremany other Oracle built-in functions to do all sorts of weird andwonderful things (see Oracle documentation)

 SIN(n), COS(n), and TAN(n) Sine, cosine, and tangent.

 ASIN(n), ACOS(n), and ACOS(n) Arcsine, arccosine, and

arctan-gent (the inverse of sine, cosine, and tanarctan-gent)

 SINH(n), COSH(n), and TANH(n) Hyperbolic sine, cosine, and

tangent

 EXP(n), LN(n), and LOG(n) e raised to the nth power, the natural

logarithm, and the logarithm

Here is a query using some of the number functions mentioned.The query uses the STUDIOTIME table and applies various func-tions to the AMOUNT_CHARGED column values The result isshown in Figure 9.7

SELECT ST.ARTIST_ID, ST.AMOUNT_CHARGED "Amount"

, ROUND(ST.AMOUNT_CHARGED,1) "Rounded to one decimal"

Trang 16

9.2 Single-Row Functions 185

, ROUND(ST.AMOUNT_CHARGED,-1) "Rounded to tens"

, TRUNC(ST.AMOUNT_CHARGED) "Truncated"

FROM STUDIOTIME ST WHERE ROWNUM < 15;

9.2.2.1 Binary Floating-Point Number Functions

As already mentioned, these functions are new to Oracle Database 10g and

could possibly be viewed as a subset of number functions, except that theyoperate specifically on binary floating-point numbers This section is par-tially repeated from Chapter 2

 TO_BINARY_DOUBLE(expression, format) and TO_BINARY_ FLOAT(expression, format) allow for conversions Essentially, these

functions are conversion functions, but they are listed here becausethey deal with binary floating-point numbers

 NANVL(value, replace) NANVL returns a replacement value if the

initial value is not a number

Figure 9.7

Number Functions

Return Results Based on the Column Value.

Trang 17

186 9.2 Single-Row Functions

 REMAINDER(n, m) This function is a remainder or modulus

function specifically for binary floating-point numbers

The next section covers date functions

ADD_MONTHS('27-AUG-02',4) = 27-DEC-02 NEXT_DAY('27-AUG-02','MONDAY') = 02-SEP-02 LAST_DAY('27-AUG-02') = 31-AUG-02

MONTHS_BETWEEN('27-AUG-02','01-JAN-02') = 7.83870968 months

Note: In the examples listed, note how dates are listed as strings and a

TO_DATE conversion function is not required This is because MON-YY is the default date format and there is an implicit string-to-datedatatype conversion The default date format can be altered Datatypes arecovered in Chapter 16

DD- SYSDATE, CURRENT_DATE, sion), LOCALTIMESTAMP(precision), and SYSTIMESTAMP.

CURRENT_TIMESTAMP(preci-SYSDATE and CURRENT_DATE find the system date setting onthe database server where CURRENT_DATE is timezone sensitive.The other functions all provide different variations on timestamps.SQL> SELECT SYSDATE FROM DUAL;

SYSDATE - 23-JAN-04 SQL> SELECT SYSTIMESTAMP FROM DUAL;

SYSTIMESTAMP - 23-JAN-04 01.03.20.661000 AM -05:00

Trang 18

9.2 Single-Row Functions 187

 ROUND(date [, format]) and TRUNC(date [, format]) These two

functions round up or truncate dates according to the format cation See Table 9.1 with date formatting rules for the ROUND andTRUNC functions

specifi-Some examples of date ROUND and TRUNC functions are asfollows Let’s say that our current date is 26-AUG-02

ROUND(SYSDATE,'YEAR') = 01-JAN-03 TRUNC(SYSDATE,'YEAR') = 01-JAN-02

ROUND(SYSDATE,'MONTH') = 01-SEP-02 TRUNC(SYSDATE,'MONTH') = 01-AUG-02

ROUND(SYSDATE,'WW') = 27-AUG-02 TRUNC(SYSDATE,'WW') = 20-AUG-02

 EXTRACT (format, date) The EXTRACT date function is

proba-bly one of the most useful and largely unknown date functions mat settings are simple, specific, and can be YEAR, MONTH, DAY,HOUR, MINUTE, SECOND, or various TIMEZONE options

For-Table 9.1 Some of the ROUND and TRUNC Function Date Formatting

Format Characters Rounding and Truncating

CC The first year in a century.

Q The nearest quarter, rounds up on the 16th of month two.

WW The same day of the week as the first day of the year.

W The same day of the week as the first day of the month.

Trang 19

SELECT EXTRACT(YEAR FROM SYSDATE) AS YEAR , EXTRACT(MONTH FROM SYSDATE) AS MONTH , EXTRACT(DAY FROM SYSDATE) AS DAY FROM DUAL;

Looking at some general date function examples, the next query usesseveral date functions The final expression uses the SYSDATE functionand subtracts two dates The results are in days, so to help compare theMONTHS_BETWEEN function and the next column, that following col-

Figure 9.8

The EXTRACT

Function Retrieves

Parts of Dates.

Trang 20

9.2 Single-Row Functions 189

umn is divided by the average number of days per month (30.44) The twovalues Months-1 and Months-2 are very close but not identical This is arather odd example, but Figure 9.9 shows the result

SELECT SESSION_DATE , ADD_MONTHS(SESSION_DATE,3) "Plus 3 Months"

, ROUND(SESSION_DATE,'Month') "Round off"

, MONTHS_BETWEEN(SYSDATE,DUE_DATE) "Months-1"

, (SYSDATE-DUE_DATE)/30.44 "Months-2"

FROM STUDIOTIME WHERE ROWNUM < 15;

The next section examines datatype conversion functions

Figure 9.9

Date Functions Use

Oracle Database

10g’s Standard Date Output Format.

Trang 21

190 9.2 Single-Row Functions

9.2.4 Datatype Conversion Functions

Before we get to examples and combining of functions, where we often useconversion functions, we will describe the most useful datatype conversionfunctions Conversion functions are important in two ways:

1 The obvious is that they allow conversions between differentdatatypes

2 The more important and less obvious is that conversion functionsallow the combination of different datatypes into expressions toproduce a single datatype result

The conversion functions we are most interested in are as listed here

 Date conversion functions:

 TO_DATE(date[, format]) Converts a string representation of

a date to a date

 TO_CHAR(date [, format]) Converts a date to a string.

 Number conversion functions:

 TO_CHAR(number [, format]) Converts a number to a string.

 TO_NUMBER(string [, format]) Converts a string to a number.

 Other conversion functions:

 TO_CLOB(string) Converts a simple string to a CLOB or

binary text object Converting from a CLOB object to a string istransparent Transparent is a computerese jargon term meaningautomatic No conversion function is required

 TO_N{CHAR|DATE|NUMBER|CLOB}(expression [, format]).

This function can be used to convert an expression, string, date,

or number from the database character set to the national ter set For example, TO_NCHAR converts an incoming value to

charac-a ncharac-ationcharac-al chcharac-archarac-acter set vcharac-alue

Now we need to examine conversion function format options sion formats are applied as a datatype conversion takes place

Conver-9.2.4.1 Number Conversion Function Formats

TO_CHAR(number[, format]) is used to convert from a number to astring, and TO_NUMBER(string [, format]) is used to convert from astring to a number As with the ROUND and TRUNC functions, there arenumerous applicable formatting rules

Trang 22

9.2 Single-Row Functions 191

A number format implies a display format imposed on a number whenthat number is converted to a string using the TO_CHAR function Theconversion is required in order to format the number into an easily readableform Some of the available number conversion format modifiers are shown

in Table 9.2

9.2.4.2 Date Conversion Function Formats

The TO_DATE(date[, format]) and TO_CHAR(date [, format]) functionsare used to convert between strings and dates Converting a date to a stringrequires that the string is a string representation of a date As with theROUND, TRUNC, and number conversion functions, there are numerousapplicable formatting rules Table 9.3 shows some of the date conversionformat modifiers

Table 9.2 Some of the Number Formatting Models

Number Format Models What Is It?

1,000,000).

5633).

C999 Leading ISO currency symbol (839 shows USD839).

trailing blank (-500 shows 500-).

trailing blank (-500 shows <500>).

sign depending on value (-500 shows –500 and 500 shows +500).

MMII).

Trang 23

192 9.2 Single-Row Functions

Here are some examples using datatype conversion functions Figure9.10 shows part of the results The TO_CHAR function for dates allowsyou to format the date in a huge variety of ways

SELECT TO_CHAR(RECORDING_DATE,'Day, Month dd, YYYY')

"Spell the day"

, TO_CHAR(RECORDING_DATE,'MM/DD/YY') "American style"

Table 9.3 Some of the Date Formatting Models

Date Format Models What Is It?

YEAR The year (2002 shows TWO THOUSAND TWO).

J Julian day or number of days since 01/01/4712 BC.

Trang 24

9.2 Single-Row Functions 193

, TO_CHAR(RECORDING_DATE,'DY, MONTH MM, YEAR')

"Spell the year"

Figure 9.10

Three Variations

on the Date Format with TO_CHAR.

Trang 25

194 9.2 Single-Row Functions

The next section covers miscellaneous functions These functions aremiscellaneous essentially because they cannot be classified as being part ofany of the previous sections

9.2.5 Miscellaneous Functions

 COALESCE(expression) The COALESCE function retrieves the

first non-null-valued expression in a list of expressions

COALESCE(NULL,NULL,'33','testing') = 33

 DECODE(expression, search, replace[, default]) This function is

similar to an IF-THEN-ELSE construct or CASE statement in gramming There is also an inline CASE statement available in Ora-cle SQL (see Chapter 14)

pro-DECODE('Harry' ,'Harry','It is Harry!' ,'Joe','It is Joe!'

Figure 9.11

Numbers Converted to

Characters Helps

Format Results.

Ngày đăng: 24/12/2013, 12:17

TỪ KHÓA LIÊN QUAN