oracle 12c 使用带有 plsql 声明的子查询分解子句

oracle 12c using subquery factoring clause with plsql declaration

我是子查询分解子句的忠实粉丝。

WITH t1 as (select 1 as id from dual)
select * from t1;

并且 oracle 12c 现在在 WITH 子句中包含一个 PL/SQL 声明部分

WITH
  FUNCTION with_function(p_id IN NUMBER) RETURN NUMBER IS
  BEGIN
    RETURN p_id;
  END;
SELECT with_function(id)
FROM   t1
WHERE  rownum = 1

但我似乎无法让他们一起工作,这可能吗?

WITH t1 as (select 1 as id from dual)
WITH  FUNCTION with_function(p_id IN NUMBER) RETURN NUMBER IS
  BEGIN
    RETURN p_id;
  END;
SELECT with_function(id)
FROM   t1
WHERE  rownum = 1;

语法请参考:
https://docs.oracle.com/database/121/SQLRF/statements_10002.htm#SQLRF01702

plsql_declarations

subquery_factoring_clause

如您所见,语法是:

WITH [ plsql_declarations ] [ subquery_factoring_clause ]

这意味着PL/SQL必须先走,然后是剩下的SQL查询,这样:

WITH 
  FUNCTION with_function(p_id IN NUMBER) RETURN NUMBER IS
  BEGIN
    RETURN p_id;
  END;
t1 as (select 1 as id from dual)
SELECT with_function(id)
FROM   t1
WHERE  rownum = 1;