[英]Calling a procedure or function in a select statement in sap hana
我一直在悶悶不樂地想着SAP HANA語法。 我一直在尋找一種編寫函數或過程並在select語句中調用該函數或過程的方法,以評估表中的列並基於if函數更改該列。
我已經創建了大多數腳本,但是replace函數無法按預期工作。 我對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
對於您描述的內容,最好使用標量用戶定義函數(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
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.