【问题标题】:IF NOT EXISTS in Oracle如果在 Oracle 中不存在
【发布时间】:2022-01-14 23:38:26
【问题描述】:

我是 Oracle 的新手,需要一些关于 SQL Server 在 Oracle 中的 IF NOT EXISTS 等效项的帮助。 如果特定角色不存在,我需要根据实体编号从角色表中找到最大角色 ID。我在下面创建了查询,但它失败(如果实体具有特定角色,它应该返回 null,如果实体没有角色,它应该返回 1,在两种情况下都返回 1)如果实体没有有任何作用。

代码:-

SELECT NVL(MAX(role_id), 0) + 1 AS RoleID from roles WHERE entity_no = '000001'
AND
    NOT EXISTS (
        SELECT 1
        FROM roles
        WHERE entity_no = '000001' AND name = 'Survey'
    )

如果一个实体没有任何角色,我需要 1 作为 RoleID,但它应该为具有该特定角色('Survey')的实体返回 null,否则返回最大 RoleID,增量为 TIA。

【问题讨论】:

  • 除了对NVL() 的调用之外,您的查询符合 ANSI 标准并且应该适用于 Oracle(以及许多其他数据库)。
  • 在没有 NVL 的情况下也尝试过,但如果实体具有该角色并且实体没有角色,则会得到相同的结果。
  • 嗨 Sunil,你所说的“失败”是什么意思?
  • 嗨@ekochergin,如果实体具有特定角色,它应该返回null,如果实体没有角色,它应该返回1。还更新了问题。
  • 如果您使用它来生成序列,那么为什么不使用序列呢?您可能不得不接受序列中会有间隙,但如果同时启动两个查询以生成 MAX 并最终得到重复值,这将比使用 MAX 和存在并发问题要好。

标签: sql oracle


【解决方案1】:

这样可以吗?在代码中读取 cmets。

  • entity_no = 00001 有调查,因此查询应返回 NULL
  • entity_no = 00002 没有调查,所以查询应该返回 1

SQL> with
  2  roles (role_id, entity_no, name) as
  3  -- sample data
  4    (select 1, '00001', 'Survey' from dual union all
  5     select 2, '00002', 'xxx'    from dual
  6    ),
  7  temp as
  8  -- does ENITITY_NO has role for NAME = Survey? If so, CNT = 1; else, CNT = 0
  9    (select entity_no,
 10            sum(case when name = 'Survey' then 1 else 0 end) cnt
 11     from roles
 12     group by entity_no
 13    )
 14  -- finally, check CNT value and return the result
 15  select case when t.cnt = 0 then 1 else null end as role_id
 16  from roles r join temp t on t.entity_no = r.entity_no
 17  where r.entity_no = '&par_entity_no';
Enter value for par_entity_no: 00001

   ROLE_ID
----------


SQL> /
Enter value for par_entity_no: 00002

   ROLE_ID
----------
         1

SQL>

【讨论】:

  • 我想我在这里造成了一些混乱,根据您的示例,它应该为 00001 返回 null,因为它具有该角色,应该为 00002(它的最大 id)返回 2,应该为 00003 返回 1。
  • 好吧,它不能为 00003 返回任何东西,因为它还不存在。对于您的其余评论,我们同意 - 00001 返回 NULL。但是,对于 00002,它实际上不应该返回 3(作为它的 MAX ID + 1)吗?如果是,那么修改SELECT为select nvl(r.role_id, 0) + case when ...(基本上就是添加NVL函数调用)。
猜你喜欢
  • 1970-01-01
  • 2011-03-10
  • 2019-07-13
  • 2010-12-14
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 2020-02-04
  • 1970-01-01
相关资源
最近更新 更多