SUBSTR functions

The SUBSTR functions (SUBSTR, SUBSTRB, and SUBSTRC) return a portion of a string, beginning at a specified position in the string.

The functions vary in how they calculate the length of the substring to return.

  • SUBSTR calculates lengths using characters as defined by the input character set.

  • SUBSTRB calculates lengths using bytes.

  • SUBSTRC calculates lengths using Unicode complete characters.

Return Value

The return value is the same data type as string.

Syntax

{SUBSTR | SUBSTRB | SUBSTRC }(string, position [, substring_length ])

Parameters

string

A text expression that is the base string from which the substring is created.

position

The position at which the first character of the returned string begins.

  • When position is 0 (zero), then it is treated as 1.

  • When position is positive, then the function counts from the beginning of string to find the first character.

  • When position is negative, then the function counts backward from the end of string.

substring_length

The length of the returned string. SUBSTR calculates lengths using characters as defined by the input character set. SUBSTRB uses bytes instead of characters. SUBSTRC uses Unicode complete characters.

When you do not specify a value for this argument, then the function returns all characters to the end of string. If you specify a value that is less than 1 or a value that is greater than the number of characters in the string, then the function returns NA.

Examples

Example 8-122 Retrieving a Character Substring

The following example returns the specified substrings of "abcdefg".

SHOW SUBSTR('abcdefg',3,4) 
cdef

SHOW SUBSTR('abcdefg',-5,4) 
cdef

Example 8-123 Retrieving a Substring Using Bytes

Assume an AL32UTF8 database character set. For the string Fußball, the following statement returns a substring 4 bytes long, beginning with the second byte.

SHOW SUBSTRB('Fußball',2,4)
ußb