SQL查询(Pro*C)如何能够找到数据库表中不存在的一组值



我有一个C/c++程序嵌入Oracle SQL调用在pro C(11.2+版本)。我有一个值列表(int)作为数组。我想通过SQL查询检查(如proc代码),其值不在DB表中。例如,假设我的值:10, 20, 30, 40, 50存储在一个数组中,并且我的DB表t1的列col1包含10, 20, 40

Select col1 from t1

将提供给我:

10
20
40

所以,我正在寻找被排除的值,即30,50。我可以通过嵌入式Pro*C SQL查询做到这一点吗?我的列表相当大,DB表有许多值。

您需要在表中设置您的值。下面是在大多数数据库中都能工作的典型方式:

with list as (
      select 10 as n union all select 20 union all select 30 union all
      select 40 union all select 50
     )
select l.*
from list l
where not exists (select 1 from t1 where col1 = l.n);

语法可能因数据库而异(from dual,子查询而不是CTE),但思想是相同的。

在Oracle中,您可以使用集合作为使用联合查询创建CTE/内联视图的替代方案:

select l.column_value as missing
from table(sys.odcinumberlist(10, 20, 30, 40, 50)) l
where not exists (select 1 from t1 where col1 = l.column_value);
   MISSING
----------
        20
        30
        50

SQL小提琴。

这里sys.odcinumberlist是一个内置的集合类型,以节省您创建自己的表类型。

除了更容易像这样输入值(IMO)之外,还可以在客户机应用程序中使用这种方法,方法是将值作为数组传递,这很有用。这里有OCI (C/c++)的例子,这里有Java的例子。

SELECT regexp_substr('10|20|30|40|50', '[^|]+', 1, ROWNUM) var
FROM dual
CONNECT BY LEVEL <= length(regexp_replace('10|20|30|40|50', '[^|]', '')) + 1
MINUS
SELECT col1 FROM t1;

最新更新