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.

The SUBSTRING() function works at the character level. The function takes three parameters: the string<br />

out of which the substring is obtained, the first character to be obtained, and how many total characters<br />

are required. Consider the following syntax:<br />

SUBSTRING(string, start_character_position, length_of_string_to_obtain)<br />

MS Access doesn’t utilize the SUBSTRING() function. Instead, it employs the MID() function, which<br />

has exactly the same syntax and works in the same way as does the SUBSTRING() function. So if you’re<br />

using MS Access, wherever you see SUBSTRING(), simply replace it with MID(). Oracle and IBM’s<br />

DB2 support SUBSTRING(), but they call it SUBSTR(). If you’re using DB2 or Oracle, wherever you<br />

see SUBSTRING(), replace it with SUBSTR().<br />

As previously stated, the position of each character within the string is often called the character index. If<br />

you want to extract the substring rox from the string Wrox Press, you would write the following function:<br />

SUBSTRING(‘Wrox Press’,2,3)<br />

Wrox Press is the string from which the substring is extracted. 2 is the character index for the first character<br />

to be extracted, in this case the letter r. Finally, 3 is the number of characters to be extracted, in this<br />

case rox.<br />

The following code uses SUBSTRING() to find out the first letter of each member’s last name and the<br />

first two letters of the name of their state of residence:<br />

SELECT LastName, SUBSTRING(LastName,1,1), State, SUBSTRING(State,1,2)<br />

FROM MemberDetails;<br />

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

LastName SUBSTRING(LastName,1,1) State SUBSTRING(State,1,2)<br />

Smith S Mega State Me<br />

Gee G New State Ne<br />

Jones J New State Ne<br />

Jones J New State Ne<br />

Jackson J New State Ne<br />

Johnson J Mega State Me<br />

Botts B Golden State Go<br />

Simons S Mega State Me<br />

Hills H New State Ne<br />

Dales D Golden State Go<br />

Doors D Mega State Me<br />

Night N Golden State Go<br />

Hawthorn H NULL NULL<br />

Manipulating Data<br />

169

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

Saved successfully!

Ooh no, something went wrong!