检查行是否存在

时间:2013-09-18 15:03:17

标签: oracle plsql plsqldeveloper

如果WHERE如下所示,则以下PL / SQL代码的行为会有所不同:

WHERE USERNAME = 'aaaaaa'

,如果看起来像这样:

WHERE USERNAME = userName

为什么userName := 'aaaaaa'的结果不一样?我究竟做错了什么? 谢谢!

declare
  isFound  NUMBER;
  userName VARCHAR2(30);
begin
  isFound  := 0;
  userName := 'aaaaaa';

  SELECT COUNT(*)
    INTO isFound
    FROM MyTable
   WHERE USERNAME = 'aaaaaa' -- userName
     AND ROWNUM = 1;

  IF isFound > 0 THEN
    dbms_output.put_line('Found');
  ELSE
    dbms_output.put_line('Not found');
  END IF;

end;

2 个答案:

答案 0 :(得分:4)

在此版本中:

  SELECT COUNT(*)
    INTO isFound
    FROM MyTable
   WHERE USERNAME = userName
     AND ROWNUM = 1;

...表格的USERNAME列正在与自身进行比较,因此它始终匹配。您没有将它与局部变量进行比较。如果您想这样做,您需要为该变量指定一个不同的名称:

declare
  isFound  NUMBER;
  localUserName VARCHAR2(30);
begin
  isFound  := 0;
  userName := 'aaaaaa';

  SELECT COUNT(*)
    INTO isFound
    FROM MyTable
   WHERE USERNAME = localUserName
     AND ROWNUM = 1;

  IF isFound > 0 THEN
    dbms_output.put_line('Found');
  ELSE
    dbms_output.put_line('Not found');
  END IF;

end;

或者正如David Aldridge建议的那样,使用标签来区分局部变量和表格列:

<<local>>
declare
  isFound  NUMBER;
  userName MyTable.USERNAME%TYPE;
begin
  isFound  := 0;
  userName := 'aaaaaa';

  SELECT COUNT(*)
    INTO isFound
    FROM MyTable
   WHERE USERNAME = local.userName
     AND ROWNUM = 1;
...

您也可以将该方法用于命名块;如果这是在函数内部,您可以将局部变量称为function_name.variable_name。由于这是一个匿名块,因此标签与function_name基本上扮演相同的角色。

文档有a section about name resolution

答案 1 :(得分:2)

您可以使用标签。

<<the_code>>
declare
  isFound  NUMBER;
  userName VARCHAR2(30);
begin
  isFound  := 0;
  userName := 'aaaaaa';

  SELECT COUNT(*)
    INTO isFound
    FROM MyTable
   WHERE USERNAME = the_code.userName
     AND ROWNUM = 1;

  IF isFound > 0 THEN
    dbms_output.put_line('Found');
  ELSE
    dbms_output.put_line('Not found');
  END IF;

end;