在 SAP HANA table 函数中使用 WITH 语句

Using WITH Statement in SAP HANA table functions

是否可以在 SAP HANA table 函数中使用 WITH 语句,或者我可以在 table 函数中使用任何替代方法吗?

CREATE OR REPLACE FUNCTION "MY_SCHEMA"."TF_TEST_1" ()
RETURNS TABLE ( 
mytext NVARCHAR(200)

) LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS
BEGIN RETURN

WITH X AS (SELECT 'asdf' AS mytext FROM dummy)
SELECT * FROM X;

END;

在 table 函数中,您需要显式地 return 一个 table with return 语句。 正如实验所示,return 中不允许使用 with(类似于 CTAS:从 selectwith 开头的语句创建 table 会引发错误)。

但是您可以将语句的结果分配给 table variable 和 return 它。

create function test_tf (x int)
returns table (
  id int
)
as begin

  res = with a as (
    select x as id
    from dummy
  )
  select *
  from a;

  return(:res);
end;

select *
from test_tf(1);


|   | ID|
|--:|--:|
|  1|  1|

但在 HANA SQLScript 中,我们更喜欢使用 table 变量而不是 with 语句,因为它们允许逐步调试代码而无需重写它或 运行 外部作为 SQL 语句,带有准备好的输入和 select 放置在每个 with 之后。您可以即时声明它们,这样您就不必预先声明一些奇怪的东西。所以重写的方法是:

alter function test_tf (x int)
returns table (
  id int
)
as begin

  /*with a as */
  a =
    select x as id
    from dummy
  ;
  
  res = 
    select *
    from :a;

  return(:res);
end;

注意:唯一的事情是在访问它时在 table 变量之前添加一个冒号,以便解析器可以将它与 table 名称区分开。

如果您想在作为函数发布之前调试您的代码,只需将 create function 语句替换为 do 并将 return 替换为 select * from <return variable>。要查看中间结果,您仍然需要将 select * from :table_var 放在中间的某个位置,因为据我所知,匿名块不允许使用调试器进行 debuggind。

do (in x int => ?)
begin

  /*with a as */
  a =
    select x as id
    from dummy
  ;
  
  res = 
    select *
    from :a;

  select * from :res;
  --return(:res);
end;