Search code examples
sqlsyntax-errordynamic-sqlhanahana-sql-script

Dynamic SQL Syntax Error SQLScript SAP HANA


I have dynamic SQL in a Stored Procedure.

The procedure takes three parameters:

  • DimPartialName
  • ColumnName
  • UploadID

Here is the procedure:

PROCEDURE "Schema"."DeletefromDIM" (In DimPartialName NVARCHAR(50), In 
IDColumnName NVARCHAR(50), IN UploadID NVARCHAR(36) ) 
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER 
--DEFAULT SCHEMA <default_schema_name>
AS
BEGIN
EXECUTE IMMEDIATE
'select distinct "'|| IDColumnName ||'" from 
"Schema"."ZT.'|| DimPartialName ||'" dim
LEFT JOIN "Schema"."SourceTable" raw on 
dim."AUDIT.CREATED_ON" = raw."Audit.CREATED_ON"
where "UPLOAD_UUID" = ' || UploadID ||' ';
End;

And the Error:

SAP DBTech JDBC: [257]: sql syntax error: "Schema"."DeletefromDIM": line 15 col 1 (at pos 520): [257] (range 3) sql syntax error exception: sql syntax error: incorrect syntax near "-": line 3 col 41 (at pos 214)

when I run this SQL in the console and substitute in my inputs, then it works fine:

select distinct "BRANDID" from "Schema"."ZT.BRAND" dim
LEFT JOIN "Schema"."SourceTable" raw on dim."AUDIT.CREATED_ON" = raw."Audit.CREATED_ON"
where "UPLOAD_UUID" = 'f889e016-1364-4aac-9536-037d932c55b5'; 

The error doesn't really make sense because not only is there no "-" at that position, there is no dash in the entire statement.


Solution

  • You should check the generated SQL string by selecting it for output, like so:

    BEGIN
    
            select                'select distinct "'|| IDColumnName ||'" from 
                            "Schema"."ZT.'|| DimPartialName ||'" dim
                            LEFT JOIN "Schema"."SourceTable" raw on 
                            dim."AUDIT.CREATED_ON" = raw."Audit.CREATED_ON"
                            where "UPLOAD_UUID" = ' || UploadID ||' ' as SQLTEXT from dummy;
    
    End;
    

    If you do this, you'll discover that the SQL statement generated looks like this (for input of 'X', 'Y', 'Z'):

    select distinct "Y" from 
                        "Schema"."ZT.X" dim
                        LEFT JOIN "Schema"."SourceTable" raw on 
                        dim."AUDIT.CREATED_ON" = raw."Audit.CREATED_ON"
                        where "UPLOAD_UUID" = Z 
    

    Notice how the WHERE condition "UPLOAD_UUID" = Z lacks single quotation marks around the Z.

    Changing the statement to

    BEGIN
    
        execute immediate 
                      'select distinct "'|| :IDColumnName ||'" ' 
                   || 'from '
                   || '"Schema"."ZT.'|| :DimPartialName ||'" dim '
                   || 'LEFT JOIN "Schema"."SourceTable" raw on '
                   || 'dim."AUDIT.CREATED_ON" = raw."Audit.CREATED_ON" '
                   || 'where "UPLOAD_UUID" = ''' || :UploadID ||''' ';
    
    END;
    

    should fix the issue.