`select true into bool_variable from table_name where column_name = in limit 1` vs `select column = in into bool_variable from table_name limit 1;`

问题描述 投票:0回答:1

我正在尝试执行 PL/SQL 查询。目标是查看是否至少有一行

column_name
中的列
table_name
对应于输入值 input 并将结果分配给 bool_variable

我的问题是:

select true into bool_variable from table_name where column_name = input limit 1;

产生与

相同的结果
select column = input into bool_variable from table_name;

最终目标是使用

bool_variable

编写 if/else 条件

例如,

IF bool_variable then
   ....
END IF

我尝试根据查询结果分配一个布尔变量。

sql plsql
1个回答
0
投票

第一个语句无效,您不能在

SELECT
语句中选择布尔值(至少据我所知)。此外,(Oracle 的)PL/SQL 中没有
LIMIT
子句。

SQL> declare
  2    bool_variable boolean;
  3  begin
  4    select true into bool_variable from dual;
  5  end;
  6  /
  select true into bool_variable from dual;
         *
ERROR at line 4:
ORA-06550: line 4, column 10:
PL/SQL: ORA-00904: "TRUE": invalid identifier
ORA-06550: line 4, column 3:
PL/SQL: SQL Statement ignored

第二条语句也是无效的(语法错误),它不起作用。

select column = input into bool_variable from table_name;

这里的示例展示了一种方法:

SQL> set serveroutput on;
SQL> declare
  2    l_cnt         number;
  3    bool_variable boolean;
  4  begin
  5    begin
  6      select 1
  7      into l_cnt
  8      from dual
  9      where exists (select null
 10                    from dept                 --> this is your "table name"
 11                    where deptno = 99);       --> this is your "column name"
 12    exception
 13      when no_data_found then
 14        l_cnt := 0;
 15    end;
 16
 17    bool_variable := case when l_cnt = 1 then true else false end;
 18
 19    if bool_variable then
 20       dbms_output.put_line('True');
 21    else
 22       dbms_output.put_line('False');
 23    end if;
 24  end;
 25  /
False

PL/SQL procedure successfully completed.

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.