我有一个问题是逐字循环一个字符串。我将有一个输入字符串“苏丹中国美国非洲”,我有查询表有3行苏丹,中国,美国。所以我需要写PL / SQL函数,它将循环输入字符串“Sudan China USA Africa”,从右到左(在这种情况下非洲到苏丹)的每个单词,并尝试从查找表中找到匹配,它发现任何匹配单词(从右边第一次出现,在这种情况下是美国)它将停止循环并返回单词(USA)。总而言之,我们必须逐字循环从输入字符串的右侧到左侧,并返回查找表中可用的第一个匹配字。
答案 0 :(得分: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;
答案 1 :(得分: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