Oracle,判断value是否为null

Oracle, determine if value is null

如果我运行在sqldeveloper(或sqlplus)中进行以下查询:

    select *
    from passwordlog
    where exists(
              select USERUID 
              from otherTable 
              where uid=2
            );

where exists 的计算结果为 false,结果为空。

结果既不是 null 也不是布尔值,所以我测试这个结果的长度是否大于 1。

但我刚刚开始怀疑。结果究竟如何?它是一个空字符串吗?还是空?有没有比检查返回字符串的长度更好的方法来执行此检查?

我希望能够做这样的事情(假设我们有 Oracleconnection、OracleDataAdapter 等):

string query = select *
               from passwordlog
               where exists(
                   select USERUID 
                   from otherTable 
                   where uid=2
              );

然后在 C# 方法中:

public void SomeMethod() {
   if(query == null) { } ...
      or maybe
   if(query == false) { } ...
} 

谢谢

因为您只检查某些东西是否 "exists"(至少,这就是您的 C# 代码的样子),如果您使用 select count(*) 而不是 select *,您可能会修复它,因为 COUNT 将 return 0(零),如果没有什么可以 returned,所以你可以很容易地在你的 C# 代码中检查它。

这是一个空的结果集或记录集。所以下面的查询可以简化为。因此不会选择任何行,因为谓词是 false。因此,您检查 no.of rows > 1 是否也始终为 false

select *
from passwordlog
where false

检查一下,如果你只是做下面的事情,记录数将是0

select count(*) from passwordlog where 1 = 0

像这样修改代码并尝试..

    select count(*)
    from  passwordlog
    where exists (select useruid
                  from othertable 
                  where uid=2)

通常在 EXISTS 子查询中,您会引用主查询中的记录,例如查看密码日志的用户标识是否存在 otherTable 条目:

select *
from passwordlog p
where exists (select * from otherTable o where o.uid = p.uid);

但是,您的子查询与主查询不相关。无论您查看的是什么密码日志记录,它要么为真,要么为假。这意味着您要么 select 所有密码日志记录,要么根本 none。

关于你的问题当表达式求值为false时(otherTable中没有uid=2记录):这种情况你select没有记录。您在询问这是一个空字符串还是 null,但请记住:您没有 selected 行。如果您 select 编辑了一些行,您可能会要求特定行中的特定列,例如:第一行中的密码是什么或第二行中的用户 ID 是什么?但是你当然不能问 "what is the columns in the zeroth row".

如果只是检查otherTable中是否存在uid=2的记录,那就是

select exists (select * from otherTable where uid = 2);

在标准中 SQL returning 一个布尔值。但是,在 Oracle 中,您必须始终从 table(一行的双 table)中 select,并且没有布尔数据类型。因此:

select 
  case when exists (select * from otherTable where uid = 2) then 1 else 0 end
from dual;

另一种选择是对记录进行计数,但是当您只想知道是否至少有一条记录匹配时,您不想读取所有记录并一直计数。在 Oracle 中,您可以为此使用 rownum:

select count(*)
from otherTable
where uid = 2 and rownum = 1;

Oracle 将在第一次匹配时停止,因此 return 为 0 或 1,具体取决于 otherTable 中是否存在 uid=2 记录。