hana - 在 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;
解决方案
在表函数中,您需要显式返回带有return
语句的表。如实验所示,with
内部是不允许的return
(类似于 CTAS: create table from select
statement started with with
throws 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
和。要查看中间结果,您仍然需要放置在两者之间的某个位置,因为据我所知,匿名块不允许使用调试器进行调试。return
select * 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;
推荐阅读
- for-loop - Verilog for 循环无法使用 oasys 进行综合
- android - Qt/QML Android 10 崩溃“中止”
- angular - 如何使用无尽的 JSON 绑定树结构 UI - Angular 8
- angular - 如何在具有 cPanel 的实时服务器上部署具有独立前端(角度)和后端(弹簧启动)的应用程序?
- javascript - 如何路由到Vue中随机生成的firestore id?
- react-native - 在反应本机应用程序中添加清除缓存选项
- python - 如何在不使用“0”或“无”的情况下初始化python中的任何整数
- javascript - 以反应方式选择所有列表项的正确方法是什么
- rust - Rust - 特征绑定取决于特征?
- json - 杰克逊在@ManyToMany 关系中的序列化问题