The POSITION function searches for a string in a character value
expression. The first character value expression is also called
a search string. The second character value expression is also
called a source string. If the search string is located, the
POSITION function returns a numeric value that indicates the
position of the search string in the source string. The returned
numeric value is the absolute position of the search string in
the source string starting with 1. The match between the search
string and the source string is case sensitive.
If the search string is not found in the source string, the
POSITION function returns a zero (0) value. If any of the
strings is NULL, the result is NULL.
The FROM clause of the POSITION function is an extension to the
ANSI/ISO SQL standard and allows searching to begin from any
location.
Examples: Using the POSITION function
Example 1: Using the POSITION function in a SELECT statement
SQL> SELECT COLLEGE_NAME,
cont> POSITION ('University' IN COLLEGE_NAME)
cont> FROM COLLEGES
cont> WHERE COLLEGE_NAME LIKE '_%University%';
COLLEGE_NAME
American University 10
Drew University 6
Harvard University 9
Purdue University 8
Stanford University 10
Yale University 6
6 rows selected
Example 2: Using the POSITION function with the SUBSTRING clause
SQL> SELECT SUBSTRING (COLLEGE_NAME FROM 1 FOR
cont> POSITION ('University' IN COLLEGE_NAME) -1)
cont> FROM COLLEGES
cont> WHERE COLLEGE_NAME LIKE '_%University%';
American
Drew
Harvard
Purdue
Stanford
Yale
6 rows selected
Example 3: Using the POSITION function to find individual words.
Because this example uses the TRACE statement, you must define
the RDMS$DEBUG_FLAGS logical name to "Xt".
SQL> BEGIN
cont> DECLARE :TXT VARCHAR(100);
cont> DECLARE :RES VARCHAR(20);
cont> DECLARE :ST, :EN INTEGER;
cont> --
cont> SET :TXT = 'Some words and phrases';
cont> --
cont> -- Start at the beginning
cont> --
cont> SET :ST = 1;
cont> --
cont> -- Loop over all the text looking for space delimiters
cont> --
cont> WHILE :ST <= CHAR_LENGTH(:TXT)
cont> LOOP
cont> SET :EN = POSITION (' ' IN :TXT FROM :ST);
cont> IF :EN = 0 THEN
cont> --
cont> -- No trailing spaces, so assume space after last character
cont> --
cont> SET :EN = CHAR_LENGTH(:TXT) + 1;
cont> END IF;
cont> SET :RES = SUBSTRING(:TXT FROM :ST FOR :EN - :ST);
cont> IF CHAR_LENGTH (TRIM (:RES)) > 0 THEN
cont> --
cont> -- Have a word to display
cont> --
cont> TRACE 'Word: "', :RES, '"';
cont> END IF;
cont> --
cont> -- Advance the start position
cont> --
cont> SET :ST = :EN + 1;
cont> END LOOP;
cont> END;
~Xt: Word: "Some "
~Xt: Word: "words "
~Xt: Word: "and "
~Xt: Word: "phrases "