Search code examples
procedurehana

HANA procedure for CONDENSE and SPLIT


I am trying to condense and split a string into single rows, e.g.

A     B C

into

A
B
C

So far, the below procedure works fine for CALL Z_SPLITROW('A B C'), but not if I have more whitespace between the chars. Any ideas?

CREATE PROCEDURE Z_SPLITROW(TEXT nvarchar(100))
AS
BEGIN
  declare _items nvarchar(100) ARRAY;
  declare _text nvarchar(100);
  declare _index integer;
  _text := :TEXT;
  _index := 1;

  WHILE LOCATE(:_text,' ') > 0 DO
  _items[:_index] := SUBSTR_BEFORE(:_text,' ');
  _text := SUBSTR_AFTER(:_text,' ');
  _index := :_index + 1;
  END WHILE;
  _items[:_index] := :_text;

  rst = UNNEST(:_items) AS ("items");
  SELECT * FROM :rst;
END; 

Solution

  • To filter out a flexible number of whitespace characters, you can use REPLACE_REGEXPR:

    select 'A     B C' as orig,
            replace_regexpr ( '[[:space:]]+' 
                            IN  'A     B C'
                            WITH ' ') as repl
    from dummy;
    
    
    ORIG     |  REPL 
    ---------+-------
    A     B C|  A B C