动态 SQL 语法错误 SQL 编写 SAP HANA 脚本

Dynamic SQL Syntax Error SQLScript SAP HANA

我在存储过程中有动态 SQL。

程序采用三个参数:

程序如下:

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;

错误:

SAP DBTech JDBC:[257]:sql 语法错误:"Schema"。"DeletefromDIM":第 15 列第 1 行(位置 520):[257] (范围 3)sql 语法错误异常:sql 语法错误:“-”附近的语法不正确:第 3 行第 41 行(位置 214)

当我在控制台中 运行 这个 SQL 并替换为我的输入时,它工作正常:

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'; 

错误并没有真正意义,因为不仅那个位置没有“-”,整个语句中也没有破折号。

您应该通过选择输出字符串来检查生成的 SQL 字符串,如下所示:

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;

如果这样做,您会发现生成的 SQL 语句如下所示(对于 '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 

请注意 WHERE 条件 "UPLOAD_UUID" = Z 如何在 Z 周围缺少单引号。

将语句更改为

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;

应该可以解决这个问题。