Search code examples
sqlsybasesqlanywhere

SAP Sybase WHILE inside of FOR LOOP


I'm trying to get this to work, but it keeps coming up with

Could not execute statement.

Syntax error near 'BEGIN' on line 14
SQLCODE=-131, ODBC 3 State="42000"
Line 1, column 1
You can continue executing or stop.

The code is the following:

IF VAREXISTS('@count') = 0  THEN CREATE VARIABLE @count  int; END IF;
IF VAREXISTS('@string') = 0  THEN CREATE VARIABLE @string char(50); END IF;
IF VAREXISTS('@found') = 0  THEN CREATE VARIABLE @found char(50); END IF;
IF VAREXISTS('@result') = 0  THEN CREATE VARIABLE @result char(50); END IF;
IF VAREXISTS('@fieldsToSearch') = 0  THEN CREATE VARIABLE @fieldsToSearch long varchar; END IF;

SET @count = 0;
SET @string = '';
SET @found = '';
SET @result = '';
SET @fieldsToSearch = '';

FOR LoopGetForeignChar AS CursGetForeignChar Dynamic Scroll CURSOR FOR ( -- Line 1
    SELECT
        row_value stringToSearch
    FROM
        sa_split_list(@fieldsToSearch) 
    WHERE
        A1 <> '' 
    ORDER BY A1
    )
DO
    SET @string = stringToSearch;

    WHILE @count <= Length(@string)
    BEGIN                                                                -- Line 14
        SET @found = (SELECT SUBSTR(@String, @count, 1) WHERE SUBSTR(@String, @count, 1) NOT REGEXP '[a-zA-Z0-9]*')
        SET @result = @result + (SELECT STRING(@found,'x') WHERE LOCATE(@result, @found) = 0 )
        SET @count = @count + 1
    END

END FOR;

I have checked and @fieldsToSearch contains a list of alpha-numerical strings separated by commas.

Work Logic:

  • Split a list of strings into rows
  • Check each row to see if it contains any other character than '[a-zA-Z0-9]*'
  • If it does, check if it that character is already in @results, if not, add it.

This is part of a bigger SQL that works up until this point.


Solution

  • Turns out that the FOR statements are WATCOMSQL whilst the

    WHILE something
    BEGIN 
    <do this>
    END 
    

    is TRANSACTSQL.

    Solution: Use the WATCOMSQL version of the WHILE Statement which is:

    WHILE something LOOP
    <do this>
    END LOOP