创建 SQL 宏时如何使用正确的语法?

How to use proper syntax when creating SQL Macro?

使用 Oracle SQL Developer,我正在尝试使这个 Web (link) 示例正常工作:

CREATE OR REPLACE FUNCTION concat_self(str VARCHAR2, cnt PLS_INTEGER)
                    RETURN VARCHAR2 SQL_MACRO(SCALAR)
IS BEGIN            RETURN 'rpad(str, cnt * length(str), str)';
END;
/

但是我得到了那些我不理解的错误:

Function CONCAT_SELF compiled

LINE/COL  ERROR
--------- -------------------------------------------------------------
2/37      PLS-00103: Encountered the symbol "SQL_MACRO" when expecting one of the following:     . @ % ; is authid as cluster order using external character    deterministic parallel_enable pipelined aggregate    result_cache accessible 
3/4       PLS-00103: Encountered the symbol "BEGIN" when expecting one of the following:     not null of nan infinite dangling a empty 
5/0       PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:     end not pragma final instantiable order overriding static    member constructor map 
Errors: check compiler log

对于 PL/SQL 引擎识别 SQL_MACRO 关键字的任何 Oracle 实例,您的代码都是完美的 'valid'。

一旦您意识到数据库不理解您的要求,错误就开始变得更有意义了——它无法识别 'SQL_MACRO' 是 CREATE OR 的有效组件替换函数 PL/SQL 库。

这些错误可以让您了解数据库的 PL/SQL 和 SQL 解析器如何处理您的请求并将其分解为它知道如何处理的内容。

第一个错误之后的所有内容都是关于解析器无法通过它遇到的第一个问题。

此功能是在数据库的 21c 版本中引入的,如 21c New Features Guide.

中所述

You can create SQL Macros (SQM) to factor out common SQL expressions and statements into reusable, parameterized constructs that can be used in other SQL statements. SQL macros can either be scalar expressions, typically used in SELECT lists, WHERE, GROUP BY and HAVING clauses, to encapsulate calculations and business logic or can be table expressions, typically used in a FROM clause.

SQL macros increase developer productivity, simplify collaborative development, and improve code quality.