2014-09-05 110 views
-1

我有一個字循環逐字串的問題。我會輸入字符串「蘇丹中國美國非洲」,我有查詢表有3行蘇丹,中國,美國。因此,我需要寫入PL/SQL函數,該函數將循環輸入字符串「蘇丹中國美國非洲」,從右到左(在這種情況下,非洲到蘇丹)每個單詞,並嘗試從查找表中找到匹配,並找到任何匹配詞(右邊的第一個詞,在本例中是USA),它將停止循環並返回單詞(USA)。因此總結一下,我們必須逐字從一個輸入字符串的右到左循環,並返回查找表中可用的第一個匹配字。在PL/SQL中循環遍歷字

+0

背後從右到左搜索單詞的原因是什麼?你是否試圖解決你的問題?你能用當前的進度發佈你的代碼嗎? – yamny 2014-09-05 07:44:05

+0

目前我在使用instr函數查找字符串中第一次出現任何關鍵字。因爲它在遠程機器上,我無法共享我現有的代碼。 – Sid 2014-09-05 07:51:03

回答

1

這可以通過單個SQL查詢來完成,例如,

WITH mydata AS 
    (SELECT 1 AS id, 'Sudan China USA Africa' AS string FROM dual 
    UNION ALL 
    SELECT 2  , 'China Europe Sudan Asia'   FROM dual 
) 
    , lookup AS 
    (SELECT 'Sudan' AS word FROM dual 
    UNION ALL 
    SELECT 'China' FROM dual 
    UNION ALL 
    SELECT 'USA' FROM dual 
) 
SELECT t.id 
    , max(t.word) KEEP (DENSE_RANK LAST ORDER BY t.pos) lastword 
FROM (SELECT mydata.id 
      , pos.column_value AS pos 
      , regexp_substr(mydata.string, '([^ ])+', 1, pos.column_value) AS word 
     FROM mydata 
      CROSS JOIN 
      TABLE 
       (CAST 
        (MULTISET 
        (SELECT level 
        FROM dual 
        CONNECT BY level <= regexp_count(mydata.string, '([^ ])+') 
        ) AS sys.odciNumberList 
       ) 
      ) pos) t 
    INNER JOIN lookup l 
     ON (t.word = l.word) 
GROUP BY t.id 

     ID LASTWORD    
---------- ----------------------- 
     1 USA      
     2 Sudan     
1
declare 

function searchWord(inputString in varchar2) return varchar2 
is 

TYPE arrayWord IS TABLE OF VARCHAR2(32767) INDEX BY PLS_INTEGER; 
word arrayWord; 
tmpStr varchar2(32767); 
i  pls_integer := 0; 
tmp  number; 
begin 
tmpStr := inputString; 
loop 
    word(i) := (substr(tmpStr,1, instr(tmpStr,' ')-1)); 
    tmpStr := substr(tmpStr, instr(tmpStr,' ')+1); 
    if instr(tmpStr,' ') = 0 then 
    i := i+1; 
    word(i):= tmpStr; 
    exit; 
    end if; 
    i := i+1; 
end loop; 

if word.count > 0 then 
    for i in reverse word.first..word.last 
    loop 
    select count(*) into tmp from t1 t where t.word = word(i) and rownum = 1; 
    if tmp != 0 then 
     return word(i); 
    end if; 
    end loop; 
end if; 
return null; 

end searchWord; 

begin 
dbms_output.put_line(searchWord('Sudan China USA Africa')); 
end;