20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5<br />

174<br />

In Oracle and IBM’s DB2, the following <strong>SQL</strong> is correct:<br />

SELECT LastName, CONCAT(LOWER(SUBSTR(LastName,1,1)),<br />

SUBSTR(LastName,2,LENGTH(LastName) - 1))<br />

FROM MemberDetails;<br />

Although the function names are different among the different database systems, the principles are the<br />

same, so the examples here concentrate on the <strong>SQL</strong> Server version. The tricky part of the <strong>SQL</strong> is the line<br />

shown below, so it’s helpful to break it down into parts:<br />

LOWER(SUBSTRING(LastName,1,1)) + SUBSTRING(LastName,2,LEN(LastName) - 1)<br />

The first part is as follows:<br />

LOWER(SUBSTRING(LastName,1,1))<br />

This is the bit that changes the case of the first letter to lowercase. SUBSTRING(LastName,1,1) extracts<br />

the first character, and then the LOWER() function converts that character to lowercase.<br />

The second part is as follows:<br />

SUBSTRING(LastName,2,LEN(LastName) - 1)<br />

This part extracts all the characters from the string except the first one. The code uses the function to find<br />

out how many characters there are and passes as its argument of the SUBSTRING() function that value<br />

minus 1 as the number of characters to be extracted.<br />

The two parts are then concatenated, or joined together, using the + concatenation operator.<br />

Executing the query yields the following results:<br />

LastName LOWER(SUBSTRING(LastName,1,1)) + SUBSTRING(LastName,2,LEN(LastName) - 1)<br />

Smith smith<br />

Simons simons<br />

Night night<br />

Jones jones<br />

Jones jones<br />

Johnson johnson<br />

Jackson jackson<br />

Hills hills<br />

Hawthorn hawthorn<br />

Gee gee

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!