List of Words in a String using SQLScript for SAP HANA
This SAP HANA SQLScript tutorial shows how to get the list of words in a given string or sentence as resultset of a SELECT statement. For this sample SQLScript code, we will use a global temporary table, While loop and SQLScript string functions Locate and Left.
First of all SQLScript developer will require a temporary table to store the words found in the given string variable.
In order to use the temporary table, we need to create it as global temporary table
The reason why I preferred global temporary table to local temporary table is that; we cannot insert data into temporary local tables.
The first section if for creation of the temporary table that I need formed of only one column containing a single word for each entry.
Then an anonymous block with WHILE loop is executed including the SQLScript codes to search for space character in the string variable.
String fragments between spaces are considered as words.
Here is the output of the above SQLScript on SQL Console
The SQLScript LOCATE string function is used to get the position of space characters in a given string variable.
By using the SQLScript LEFT string function, the string fragment on the left side of the space character is inserted into the temporary table as a new word record.
HANA SQLScript Function to Count Words
Above SQLScript code can be converted into a SQL function that will return the number of words in a given input string parameter.
Here is the source codes of HANA Database SQLScript function used for word count named also WordCount
This SQLScript function can be used as seen in following SQL examples. First sample is counting words in input string parameter.
Second SQL sample is to count words in string column contents on a SAP HANA database table using our SQLScript function WordCount()