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

SQL VISUAL QUICKSTART GUIDE- P17 docx

10 294 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 178,08 KB

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

Nội dung

To convert a string to uppercase or lowercase: ◆ To convert a string to uppercase, type: UPPERstring or To convert a string to lowercase, type: LOWERstring string is a string expression

Trang 1

Changing String Case

Use the function UPPER()to return a string

with lowercase letters converted to

upper-case, and use the function LOWER()to return

a string with uppercase letters converted to

lowercase The functions’ important

charac-teristics are:

A cased character is a letter that can be

lowercase (a) or uppercase (A).

◆ Case changes affect only letters Digits,

punctuation, and whitespace are left

unchanged

◆ Case changes have no effect on empty

strings (‘’)

◆ If its argument is null, UPPER()and

LOWER()return null (But see the Oracle

exception in the DBMS Tip in this section.)

Case-Insensitive Comparisons

In DBMSs that perform case-sensitive

WHERE-clause comparisons by default,

UPPER()orLOWER()often is used to make case-insensitive comparisons:

WHERE UPPER(au_fname) = ‘JOHN’

If you’re sure that your data are clean, it’s faster to look for only reasonable letter combinations than to use case functions:

WHERE au_fname = ‘JOHN’

OR au_fname = ‘John’

UPPER()andLOWER()affect characters with diacritical marks (such as accents and umlauts): UPPER(‘ö’)is‘Ö’, for exam-ple If your data contain such characters and you’re making case-insensitive com-parisons such as

WHERE UPPER(au_fname) = ‘JOSÉ’

make sure that your DBMS doesn’t lose the marks on conversion UPPER(‘Jos é ’)

Trang 2

To convert a string to uppercase

or lowercase:

◆ To convert a string to uppercase, type:

UPPER(string) or

To convert a string to lowercase, type:

LOWER(string) string is a string expression such as a

column that contains character strings,

a string literal, or the result of an opera-tion or funcopera-tion that returns a string

(Listings 5.15 and 5.16, Figures 5.15 and 5.16).

✔ Tips

■ You can use UPPER()andLOWER()in

SELECT,WHERE, and ORDER BYclauses or anywhere an expression is allowed

■ UPPER()andLOWER()don’t affect charac-ter sets with no concept of case (such

as Hebrew and Chinese)

upper- and lowercase functions are UCase(string)andLCase(string)

To run Listings 5.15 and 5.16, change the case expressions to (Listing 5.15):

LCase(au_fname) UCase(au_lname)

and (Listing 5.16):

UCase(title_name) LIKE ‘%MO%’

Oracle treats an empty string as null:

UPPER(NULL) andLOWER(NULL)return ‘’ See the DBMS Tip in “Nulls” in Chapter 3 Your DBMS might provide other string-casing functions to, say, invert case or

Listing 5.15 List the authors’ first names in lowercase

and last names in uppercase See Figure 5.15 for

the result.

SELECT LOWER(au_fname) AS "Lower",

UPPER(au_lname) AS "Upper"

FROM authors;

Listing

Lower Upper

-

-sarah BUCHMAN

wendy HEYDEMARK

hallie HULL

klee HULL

christian KELLS

KELLSEY

paddy O'FURNITURE

Figure 5.15 Result of Listing 5.15.

Listing 5.16 List the titles that contain the characters

MO, regardless of case All the letters in the LIKE

pattern must be uppercase for this query to work See

Figure 5.16 for the result.

SELECT title_name

FROM titles

WHERE UPPER(title_name) LIKE '%MO%' ;

Listing

title_name

-200 Years of German Hu mo r

I Blame My Mo ther

Figure 5.16 Result of Listing 5.16.

Trang 3

Trimming Characters

Use the function TRIM()to remove unwanted characters from the ends of a string The function’s important characteristics are:

◆ You can trim leading characters, trailing characters, or both (You can’t use TRIM()

to remove characters from within a

string.)

◆ By default, TRIM()trims spaces, but you can strip off any unwanted characters, such as leading and trailing zeros or asterisks

◆ TRIM()typically is used to format results and make comparisons in a WHEREclause

◆ TRIM()is useful for trimming trailing spaces from CHARvalues Recall from

“Character String Types” in Chapter 3 that DBMSs add spaces automatically to the end of CHARvalues to create strings of exactly a specified length

◆ Trimming has no effect on empty strings (‘’)

◆ If any argument is null, TRIM()returns

null (But see the Oracle exception in

the DBMS Tip in this section.)

Trang 4

To trim spaces from a string:

◆ Type:

TRIM([[LEADING | TRAILING | BOTH]

FROM] string) string is a string expression such as a

column that contains character strings,

a string literal, or the result of an opera-tion or funcopera-tion that returns a string

Specify LEADINGto remove leading spaces, TRAILINGto remove trailing spaces, or BOTHto remove leading and trailing spaces If this specifier is omit-ted, BOTHis assumed (Listing 5.17 and Figure 5.17).

Listing 5.17 This query strips leading, trailing, and

both leading and trailing spaces from the string

‘ AAA ‘ The < and > characters show the extent of

the trimmed strings See Figure 5.17 for the result.

SELECT

'<' || ' AAA ' || '>'

AS "Untrimmed",

'<' || TRIM(LEADING FROM ' AAA ') || '>'

AS "Leading",

'<' || TRIM(TRAILING FROM ' AAA ') || '>'

AS "Trailing",

'<' || TRIM(' AAA ') || '>'

AS "Both";

Listing

Untrimmed Leading Trailing Both

-< AAA > -<AAA > -< AAA> -<AAA>

Figure 5.17 Result of Listing 5.17.

Trang 5

To trim characters from a string:

◆ Type:

TRIM([LEADING | TRAILING | BOTH]

‘trim_chars’ FROM string)

string is the string to trim, and trim_chars

is one or more characters to remove

from string Each argument is a string

expression such as a column that

con-tains character strings, a string literal,

or the result of an operation or function

that returns a string Specify LEADING

to remove leading characters, TRAILINGto

remove trailing characters, or BOTHto

remove leading and trailing characters

If this specifier is omitted, BOTHis assumed

(Listings 5.18 and 5.19, Figures 5.18

and 5.19).

Listing 5.19 List the three-character title IDs that start

with T1, ignoring leading and trailing spaces See

Figure 5.19 for the result.

SELECT title_id FROM titles WHERE TRIM(title_id) LIKE 'T1_' ;

Listing

title_id -T10 T11 T12 T13

Figure 5.19 Result of Listing 5.19.

Listing 5.18 Strip the leading H from the authors’ last

names that begin with H See Figure 5.18 for the result.

SELECT au_lname,

TRIM(LEADING 'H' FROM au_lname)

AS "Trimmed name"

FROM authors;

Listing

au_lname Trimmed name - -Buchman -Buchman Heydemark eydemark Hull ull Hull ull Kells Kells Kellsey Kellsey O'Furniture O'Furniture

Figure 5.18 Result of Listing 5.18.

Trang 6

✔ Tips

■ You can use TRIM()inSELECT,WHERE, and

ORDER BYclauses or anywhere an

expres-sion is allowed

■ In Listing 5.8 earlier in this chapter,

I concatenated authors’ first and last

names into a single column The result,

Figure 5.8, contains a single extra space

before the author named Kellsey This

space—which separates the first and

last names in the other rows—appears

because Kellsey has no first name You

can use TRIM()to remove this leading

space Change the concatenation

expres-sion in Listing 5.8 to:

TRIM(au_fname || ‘ ‘ || au_lname)

trimming functions are

LTrim(string)to trim leading spaces,

RTrim(string)to trailing spaces, and

Trim(string)to trim both leading and

trailing spaces Use the Replace(string,

find, replacement [, start[, count[,

compare]]])function to trim nonspace

characters (actually, to replace nonspaces with empty strings) Use +to

concate-nate strings To run Listings 5.17 and

5.18, change the trim expressions to

(Listing 5.17):

‘<’ + ‘ AAA ‘ + ‘>’

‘<’ + LTRIM( ‘ AAA ‘) + ‘>’

‘<’ + RTRIM( ‘ AAA ‘) + ‘>’

‘<’ + TRIM(‘ AAA ‘) + ‘>’

and (Listing 5.18):

Replace(au_lname, ‘H’, ‘’, 1, 1)

Trang 7

In Microsoft SQL Server, the trimming

functions are LTRIM(string)to trim leading

spaces and RTRIM(string)to trim trailing

spaces Use +to concatenate strings To run

Listing 5.17, change the trim expressions to:

‘<’ + ‘ AAA ‘ + ‘>’

‘<’ + LTRIM(‘ AAA ‘) + ‘>’

‘<’ + RTRIM(‘ AAA ‘) + ‘>’

‘<’ + LTRIM(RTRIM(‘ AAA ‘)) + ‘>’

SQL Server’s LTRIM()andRTRIM()functions

remove spaces but not arbitrary trim_chars

characters You can nest and chain SQL

Server’s CHARINDEX(),LEN(),PATINDEX(),

REPLACE(),STUFF(),SUBSTRING(), and other

character functions to replicate

arbitrary-character trimming To run Listing 5.18,

change the trim expression to:

REPLACE(

➝ SUBSTRING(au_lname, 1, 1),’H’,’’)

➝ + SUBSTRING(au_lname, 2,

➝ LEN(au_lname))

To run Listing 5.19, change the trim

expres-sion to:

LTRIM(RTRIM(title_id)) LIKE ‘T1_’

In Oracle, add the clause FROM DUALto run

Listing 5.17; see the DBMS Tip in “Creating

Derived Columns” earlier in this chapter

Oracle forbids multiple characters in

trim_chars.

In DB2, the trimming functions are

LTRIM(string)to trim leading spaces and

RTRIM(string)to trim trailing spaces To run

Listing 5.17, change the trim expressions:

‘<’ || ‘ AAA ‘ || ‘>’

‘<’ || LTRIM(‘ AAA ‘) || ‘>’

‘<’ || RTRIM(‘ AAA ‘) || ‘>’

‘<’ || LTRIM(RTRIM(‘ AAA ‘)) || ‘>’

You also must add the clause FROM

SYSIBM.SYSDUMMY1to Listing 5.17; see the DBMS Tip in “Creating Derived Columns” earlier in this chapter

You can nest and chain DB2’s LENGTH(),

LOCATE(),POSSTR(),REPLACE(),SUBSTR(), and other character functions to replicate arbitrary-character trimming To run Listing 5.18, change the trim expression to:

REPLACE(

➝ SUBSTR(au_lname, 1, 1),’H’,’’)

➝ || SUBSTR(au_lname, 2,

➝ LENGTH(au_lname))

To run Listing 5.19, change the trim expression to:

LTRIM(RTRIM(title_id)) LIKE ‘T1_’

In MySQL, use CONCAT()to run Listing 5.17 (see “Concatenating Strings with ||” earlier

in this chapter) Change the concatenation expressions to:

CONCAT(‘<’,’ AAA ‘,’>’) CONCAT(‘<’,

➝ TRIM(LEADING FROM ‘ AAA ‘),

➝ ’>’) CONCAT(‘<’,

➝ TRIM(TRAILING FROM ‘ AAA ‘),

➝ ’>’) CONCAT(‘<’,TRIM(‘ AAA ‘),’>’)

Oracle treats an empty string as null:

TRIM(NULL)returns ‘’ See the DBMS Tip

in “Nulls” in Chapter 3

Your DBMS might provide padding

func-tions to add spaces or other characters to

strings The Oracle and PostgreSQL

padding functions are LPAD()andRPAD(), for example Search your DBMS documentation

for character functions or string functions.

Trang 8

Finding the Length

of a String with

CHARACTER_LENGTH()

Use the function CHARACTER_LENGTH()to return the number of characters in a string

The function’s important characteristics are:

◆ CHARACTER_LENGTH()returns an integer greater than or equal to zero

◆ CHARACTER_LENGTH()counts characters, not bytes A multibyte or Unicode char-acter represents one charchar-acter (To count bytes, see the Tips in this section.)

◆ The length of an empty string (‘’)

is zero

◆ If its argument is null, CHARACTER_LENGTH()

returns null (But see the Oracle

excep-tion in the DBMS Tip in this secexcep-tion.)

To find the length of a string:

◆ Type:

CHARACTER_LENGTH(string) string is a string expression such as a

column that contains character strings,

a string literal, or the result of an opera-tion or funcopera-tion that returns a string

(Listings 5.20 and 5.21, Figures 5.20 and 5.21).

Listing 5.20 List the lengths of the authors’ first

names See Figure 5.20 for the result.

SELECT au_fname,

CHARACTER_LENGTH(au_fname) AS "Len"

FROM authors;

Listing

au_fname Len

-Sarah 5

Wendy 5

Hallie 6

Klee 4

Christian 9

0 Paddy 5

Figure 5.20 Result of Listing 5.20 Listing 5.21 List the books whose titles contain fewer than 30 characters, sorted by ascending title length See Figure 5.21 for the result SELECT title_name, CHARACTER_LENGTH(title_name) AS "Len" FROM titles WHERE CHARACTER_LENGTH(title_name) < 30 ORDER BY CHARACTER_LENGTH(title_name) ASC ; Listing title_name Len

-1977! 5

Kiss My Boo-Boo 15

How About Never? 16

I Blame My Mother 17

Exchange of Platitudes 22

200 Years of German Humor 25

Trang 9

✔ Tips

■ You can use CHARACTER_LENGTH()in

SELECT,WHERE, and ORDER BYclauses or

anywhere an expression is allowed

■ CHARACTER_LENGTHandCHAR_LENGTHare

synonyms

■ SQL also defines the BIT_LENGTH()and

OCTET_LENGTH()functions

BIT_LENGTH(expr)returns the number

of bits in an expression;

BIT_LENGTH(B’01001011’) returns 8

OCTET_LENGTH(expr)returns the number

of bytes in an expression;

OCTET_LENGTH(B’01001011’) returns 1,

andOCTET_LENGTH(‘ABC’) returns 3

Octet length equals bit-length/8

(rounded up to the nearest integer, if

necessary) See the DBMS Tip in this

section for information about DBMS

bit- and byte-length functions

Microsoft SQL Server, the

string-length function is LEN(string)

To run Listings 5.20 and 5.21, change the length expressions to (Listing 5.20):

LEN(au_fname)

and (Listing 5.21):

LEN(title_name)

In Oracle and DB2, the string-length

function is LENGTH(string) To run Listings 5.20 and 5.21, change the length expressions to (Listing 5.20):

LENGTH(au_fname)

and (Listing 5.21):

LENGTH(title_name)

Bit- and byte-count functions vary by

DBMS Microsoft Access has Len()

Microsoft SQL Server has DATALENGTH()

Oracle has LENGTHB() DB2 has LENGTH()

MySQL has BIT_COUNT()andOCTET_ LENGTH() PostgreSQL has BIT_LENGTH()

andOCTET_LENGTH()

Oracle treats an empty string as null:

LENGTH(‘’)returns NULL Figure 5.20 will show 1 (not 0) in the next-to-last row because the author’s first name is ‘ ‘

(a space) in the Oracle database For more information, see the DBMS Tip in

“Nulls” in Chapter 3

Trang 10

Finding Substrings

Use the function POSITION()to locate a par-ticular substring within a given string The

function’s important characteristics are:

◆ POSITION()returns an integer (*0) that

indicates the starting position of a

sub-string’s first occurrence within a string

◆ If the string doesn’t contain the

sub-string, POSITION()returns zero

◆ String comparisons are case insensitive

or case sensitive, depending on your

DBMS; see the DBMS Tip in “Filtering

Rows with WHERE” in Chapter 4

◆ The position of any substring within an

empty string (‘’) is zero (But see the

Oracle exception in the DBMS Tip in

this section.)

◆ If any argument is null, POSITION()

returns null

Ngày đăng: 05/07/2014, 05:20

TỪ KHÓA LIÊN QUAN