我一直在用sap hana语法再次敲打我的脑袋。我一直在寻找一种编写函数或过程的方法,并在select语句中调用函数或过程来评估表中的列并根据if函数更改列。
我创建了大部分脚本但是替换功能没有按预期工作。我对sap hana不太熟悉,所以任何帮助都会受到赞赏。谢谢。
有人也可以告诉我如何调用该程序,因为这似乎在sap hana中有点复杂。我正在使用hana sp 10.
create procedure update_str
language sqlscript
as
ip_str varchar:= '21222212';
temp_str varchar(100) := ip_str || ',';
pos integer :=1;
begin
while(length(:temp_str) > 0 ) do
if substr(temp_str,1,1) = '1' and substr (temp_str,2,1) = '2' then
update temp_str := replace(temp_str,'12','12,');
pos := :pos + 1;
elseif substr(temp_str,1,1) = '2' and substr (temp_str,2,1) = '1' then
update temp_str := replace(temp_str,'21','2,1');
pos := :pos + 1;
elseif substr(temp_str,1,1) = '2' and substr (temp_str,2,1) = '2' then
update temp_str := replace(temp_str,'22','2,2');
pos := :pos + 1;
else;
end if;
end if;
end if;
end while;
end;
我基本上想要使用select语句运行函数或过程,并输出结果如下
我想要实现的例子
id |字符串更新|来自功能或程序的temp_str
1 | 12212 | 12,2,12
2 | 21221 | 2,12,2,1
3 | 12212 | 12,2,12
答案 0 :(得分:1)
For what you described it is best to use a scalar user-defined function (SUDF).
How to create and use those is explained extensively in the SAP HANA Developer Guide, so I won't go into details here.
I also won't discuss the logic errors in the provided code, instead here is a version that generates the output for your test data:
drop function update_str;
create function update_str (IN IP_STR varchar(100) )
returns res_str varchar(200)
language sqlscript
as
begin
declare temp_str varchar(100) := ip_str ;
-- add a comma behind twelves
temp_str := replace (:temp_str, '12', '12,');
-- add a comma between twenty-ones
temp_str := replace (:temp_str, '21', '2,1');
-- add a comma between twenty-twos
temp_str := replace (:temp_str, '21', '2,1');
-- remove last comma if there is any
if (right (:temp_str, 1) = ',' ) then
temp_str = left (:temp_str, length(:temp_str) -1 );
end if;
res_str := :temp_str;
end;
Check the code:
with test_data as
( select 1 as id, '12212' as str from dummy
union all select 2 as id, '21221' as str from dummy
union all select 3 as id, '12212' as str from dummy)
select id, str, update_str(str)
from test_data;
ID STR UPDATE_STR(STR)
1 12212 12,2,12
2 21221 2,12,2,1
3 12212 12,2,12
Depending on your actual requirement you might be able to form a regular expression that performs the same transformation. If so, you could also use the REPLACE_REGEXPR
function in SAP HANA.