这是一种方法 - 使事物井井有条,以便于维护。我假设 Oracle 12.1 或更高版本,所以我可以使用 JSON 函数(快速拆分列表);在旧版本中,您必须以不同的方式编写函数,但概念是相同的。
这个想法是编写一个函数来拆分数字列表并返回一个嵌套表。您需要一个全局(模式级别)类型,所以我先定义它,然后定义函数。然后我展示了一个示例表(您与我们共享的那个)以及查询的样子。
创建架构级类型和辅助函数
create or replace type tbl_of_num is table of number;
/
create or replace function str_to_tbl(s varchar2)
return tbl_of_num
deterministic
is
pragma udf;
ton tbl_of_num;
begin
select cast(collect(val) as tbl_of_num)
into ton
from json_table('[' || s || ']', '$[*]' columns val number path '$');
return ton;
end;
/
为测试创建小表
create table t (id, string1, string2) as
select 1, '100,101,201', '1,2,3,4' from dual union all
select 2, '100,103,201', '1,4,9,10' from dual union all
select 3, '101,102,200', '1,3,4,10' from dual
;
示例查询
首先我定义了两个绑定变量,并初始化它们。这就是您在 SQL*Plus 中的做法;您可能有其他方式将值传递给绑定变量(取决于您的应用程序、用户界面等)
variable string1 varchar2(100)
variable string2 varchar2(100)
exec :string1 := '100,201'; :string2 := '1,4'
查询和输出:
select id
from t
where str_to_tbl(:string1) submultiset of str_to_tbl(string1)
and str_to_tbl(:string2) submultiset of str_to_tbl(string2)
;
ID
----------
1
2