Selecting a subfield from a larger field

You might have a message flow that processes a message containing delimited subfields. You can code ESQL to extract a subfield from the surrounding content if you know the delimiters of the subfield.

If you create a function that performs this task, or a similar one, you can invoke it both from ESQL modules (for Compute, Database, and Filter nodes) and from mapping files (used by DataDelete, DataInsert, DataUpdate, Extract, Mapping, and Warehouse nodes).

The following function example extracts a particular subfield of a message that is delimited by a specific character.

CREATE FUNCTION SelectSubField 
       (SourceString CHAR, Delimiter CHAR, TargetStringPosition INT) 
       RETURNS CHAR
-- This function returns a substring at parameter position TargetStringPosition within the      
-- passed parameter SourceString.  An example of use might be:
-- SelectSubField(MySourceField,' ',2) which will select the second subfield from the
-- field MySourceField delimited by a blank.  If MySourceField has the value
-- "First Second Third" the function will return the value "Second"
  BEGIN
    DECLARE DelimiterPosition INT;
    DECLARE CurrentFieldPosition INT 1;
    DECLARE StartNewString INT 1;
    DECLARE WorkingSource CHAR SourceString;
    SET DelimiterPosition = POSITION(Delimiter IN SourceString);
    WHILE CurrentFieldPosition < TargetStringPosition
     	DO
     		IF DelimiterPosition = 0  THEN
   			-- DelimiterPosition will be 0 if the delimiter is not found 
         -- exit the loop
     			SET CurrentFieldPosition = TargetStringPosition;
     		ELSE
     			SET StartNewString = DelimiterPosition + 1;
     			SET WorkingSource = SUBSTRING(WorkingSource FROM StartNewString);
     			SET DelimiterPosition = POSITION(Delimiter IN WorkingSource);
     			SET CurrentFieldPosition = CurrentFieldPosition + 1;
     		END IF;
    END WHILE;
    IF DelimiterPosition > 0 THEN
       -- Remove anything following the delimiter from the string
       SET WorkingSource = SUBSTRING(WorkingSource FROM 1 FOR DelimiterPosition);     	
       SET WorkingSource = TRIM(TRAILING Delimiter FROM WorkingSource);
    END  IF;  
    RETURN WorkingSource;
END;	
Related concepts
Message flows overview
Related tasks
Designing a message flow
Defining message flow content
Related reference
Compute node
Database node
Filter node
ESQL reference
DECLARE statement
POSITION function
SET statement
SUBSTRING function
TRIM function
WHILE statement