首页 > 解决方案 > 在 SAP HANA 表函数中使用 WITH 语句

问题描述

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

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;

标签: hana

解决方案


在表函数中,您需要显式返回带有return语句的表。如实验所示,with内部是不允许的return(类似于 CTAS: create table from selectstatement started with withthrows an error)。

但是您可以将语句的结果分配给表变量并返回它。

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 中,我们更喜欢使用表变量而不是 owwith语句,因为它们允许对代码进行逐步调试,而无需重写它或在外部作为 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;

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

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

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;

推荐阅读