我想检查varchar是否包含另一个, 像这样: str1 ='1,2,3,4' str2 ='2,1'
检查str2是否在str1中。在这个例子中,它是,因为str1同时具有1和2。 我必须从java中调用一个简单的选择... 在java中我有字符串,我需要检查oracle中记录中的字符串是否在字符串中 - 但所有这些都在一个简单的选择中!
谢谢你!答案 0 :(得分:2)
You can create a simple function to split the delimited strings into collections and then use the SUBMULTISET
operator to compare them. Like this:
Oracle Setup:
CREATE TYPE VARCHAR2_TABLE AS TABLE OF VARCHAR2(4000);
/
CREATE OR REPLACE FUNCTION split_String(
i_str IN VARCHAR2,
i_delim IN VARCHAR2 DEFAULT ','
) RETURN VARCHAR2_TABLE DETERMINISTIC
AS
p_result VARCHAR2_TABLE := VARCHAR2_TABLE();
p_start NUMBER(5) := 1;
p_end NUMBER(5);
c_len CONSTANT NUMBER(5) := LENGTH( i_str );
c_ld CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
IF c_len > 0 THEN
p_end := INSTR( i_str, i_delim, p_start );
WHILE p_end > 0 LOOP
p_result.EXTEND;
p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
p_start := p_end + c_ld;
p_end := INSTR( i_str, i_delim, p_start );
END LOOP;
IF p_start <= c_len + 1 THEN
p_result.EXTEND;
p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
END IF;
END IF;
RETURN p_result;
END;
/
Query:
SELECT CASE WHEN split_String( '2,1' ) SUBMULTISET OF split_String( '1,3,2,4' )
THEN 'Matches'
ELSE 'No match'
END AS match
FROM DUAL;
Output:
MATCH
-------
Matches
答案 1 :(得分:1)
You can split each comma-separated list into individual elements, count how many items are in the second list, count how many are in both lists (via a join), and compare the counts:
with list1 (item) as (
select regexp_substr('1,2,3,4', '[^,]+', 1, level)
from dual
connect by regexp_substr('1,2,3,4', '[^,]+', 1, level) is not null
),
list2 (item) as (
select regexp_substr('2,1', '[^,]+', 1, level)
from dual
connect by regexp_substr('2,1', '[^,]+', 1, level) is not null
)
select count(list1.item), count(list2.item)
from list2
left join list1 on list1.item = list2.item;
COUNT(LIST1.ITEM) COUNT(LIST2.ITEM)
--------------------------------------- ---------------------------------------
2 2
If the second list had, say, '2,1,5' then the counts would be 2 and 3; since they are different that indicates a mismatch.
If you wanted to just get a flag saying whether they matches you coudl do something like:
with ...
select case when count(list1.item) = count(list2.item) then 1
else 0 end as matched
from list2
left join list1 on list1.item = list2.item;
When the second string is '2,1' that gets 1; when it's '2,1,5' it gets 0.
If the lists might contain duplicates when you could count distinct items. This won't work if either string is empty though.