2017-06-04 226 views
0

我一直在sap hana语法中再次敲打我的头。我一直在寻找一种方法来编写函数或过程,并在select语句中调用函数或过程来评估表中的列,并根据if函数改变列。在sap hana的select语句中调用过程或函数

我已经创建了大部分脚本,但替换函数未按预期工作。我不太熟悉sap hana,所以任何帮助将不胜感激。谢谢。

有人也可以让我知道我该怎么称呼这个程序,因为这在sap hana中似乎有点复杂。我使用花属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 |字符串已更新| 12212 | |从函数或过程
1 temp_str 12,2,12
2 | 21221 | 2,12,2,1
3 | 12212 | 12,2,12

回答

1

因为这是你所描述的最好使用标量用户定义函数(SUDF)
SAP HANA开发人员指南对如何创建和使用这些内容进行了广泛的解释,所以在此不赘述。

我也不会讨论逻辑错误中所提供的代码,而不是在这里是生成输出测试数据的版本:

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; 

检查代码:

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 

根据您的实际需求,您可能会形成执行相同转换的正则表达式。如果是这样,您还可以使用SAP HANA中的REPLACE_REGEXPR函数。

+0

感谢Lars为您提供这方面的帮助。我能够关注。非常感谢。 – MRUNIVERSE