我有一个Oracle SQL DB列,其中包含逗号分隔的值列表,作为输入,我有两个数字 - 我需要查明值列表中至少有一个数字是否在两个输入数字之间。
示例:
数据库列内容:'100, 200, 300, 400, 500'
输入:10,100
请求的输出:true(因为100在10到110之间)。
有没有办法在直接SQL(无PL / SQL)中做到这一点?
答案 0 :(得分:2)
您可以使用XMLTABLE
。
Oracle 11g R2架构设置:
create table yourtable as select '100, 200, 300, 400, 500' nums from dual;
查询1 :
WITH t(n)
AS (SELECT TO_NUMBER (column_value)
FROM yourtable,
XMLTABLE(nums)),
input(min_val, max_val)
AS (SELECT Min(TO_NUMBER(column_value)),
Max(TO_NUMBER(column_value))
FROM XMLTABLE('10,100' ))
SELECT CASE
WHEN EXISTS (SELECT 1
FROM t
WHERE t.n BETWEEN i.min_val AND i.max_val) THEN 'TRUE'
ELSE 'FALSE'
END is_between
FROM input i
<强> Results 强>:
| IS_BETWEEN |
|------------|
| TRUE |
答案 1 :(得分:1)
您可以创建如下函数:
CREATE OR REPLACE TYPE NUMBER_TABLE_TYPE AS TABLE OF NUMBER;
CREATE OR REPLACE FUNCTION SplitCSV(LIST IN VARCHAR2, Separator IN VARCHAR2) RETURN NUMBER_TABLE_TYPE IS
OutTable NUMBER_TABLE_TYPE := NUMBER_TABLE_TYPE();
BEGIN
SELECT REGEXP_SUBSTR(LIST, '[^'||Separator||']+', 1, LEVEL)
BULK COLLECT INTO OutTable
FROM dual
CONNECT BY REGEXP_SUBSTR(LIST, '[^'||Separator||']+', 1, LEVEL) IS NOT NULL;
RETURN OutTable;
END;
然后你可以使用它,例如:
WITH t AS (SELECT '100, 200, 300, 400, 500' AS val FROM dual)
SELECT distinct 'true'
FROM t
CROSS JOIN TABLE(SplitCSV(val, ','))
WHERE COLUMN_VALUE BETWEEN 10 and 80;
或者在一个SELECT中完成所有操作:
WITH t AS
(SELECT TO_NUMBER(REGEXP_SUBSTR('100, 200, 300, 400, 500', '[^,]+', 1, LEVEL)) AS NUMBERS
FROM dual
CONNECT BY REGEXP_SUBSTR('100, 200, 300, 400, 500', '[^,]+', 1, LEVEL) IS NOT NULL)
SELECT case when count(NUMBERS) > 0 then 'TRUE' else 'FALSE' end
FROM t
WHERE NUMBERS BETWEEN 10 AND 80;