sql-insertcommon-table-expressionhanahana-sql-script

Does SQLScript for SAP HANA support the use of INSERT with CTEs (Common Table Expressions)?


I know this isn't a specific bit of code or problem, but I am having trouble with a very similar issue to the person asking this (except theirs is for SQL Server): Combining INSERT INTO and WITH/CTE ...and I can't seem to find it out there on any SAP HANA help forums etc. so thought there may be an expert on here who can just give me a simple yes or no answer.

The SQL statement I am using contains multiple CTEs, but when I try to insert it tells me there is a Syntax error around the word INSERT. It is definitely laid out exactly the same as in the question I've linked above (spent hours checking), and I can post code samples if necessary but I simply want to know whether it is supported first! Thanks


Solution

  • Short answer: No, CTEs are not supported for INSERT/UPDATE statements.

    Longer answer: SQLScript's INSERT/UPDATE commands are actually "borrowed" SQL commands as the documentation explains.

    Checking the documentation for SQL INSERT we find that it supports a subquery as a source of values.

    The subquery term is defined as part of the SQL SELECT statement. Checking the documentation for SELECT shows that <subquery> and <with_clause> are different, non-overlapping terms.

    This means, that CTEs cannot be used in subqueries and therefore not be part of the subqueries used in INSERT/UPDATE commands.

    You can, however, use SQLScript table variables in INSERT statements in your SQLScript blocks, which is very similar to CTEs:

    DO BEGIN
      te_a := SELECT 10, 'xyz' as VAL from dummy;
      te_b := SELECT 20, 'abc' as VAL from dummy;
    
      te_all :=     SELECT * from :te_a
          UNION ALL SELECT * from :te_b;
    
      INSERT INTO VALS 
                 (SELECT * from :te_all);
    
    END;