2017-06-04 57 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