【问题标题】:Error: an INTO clause is expected in this SELECT statement错误:此 SELECT 语句中需要一个 INTO 子句
【发布时间】:2022-12-04 20:20:15
【问题描述】:

我将在其中编写一个 if 语句,如果条件传递需要运行第一个 select 语句,否则运行第二个。但它在此 SELECT 语句中显示一个 INTO 子句

declare
x integer;
begin
select to_char(sysdate,'hh') into x from dual;
if x > 12 then
select sysdate from dual;
else
select sysdate+1 from dual;
end if;
end;

【问题讨论】:

  • 您的 sysdate 选择没有 into 子句。
  • 您有一个带有 into 子句的 select 和两个没有 into 子句的 select。您希望这两个查询的结果发生什么变化? (顺便说一句,在那些你真的想要sysdate包括当前时间,或trunc(sysdate)得到午夜;和hh永远不会超过12,你需要hh24,但可以使用@ 987654326@ 而不是...)
  • 您不需要 3 次选择。只需使用 case 表达式。 select case when to_char(sysdate,'hh') > 12 then sysdate else sysdate + 1 end...
  • 主要意图是 if else 语句中的 select 语句应该根据我们的条件运行

标签: sql oracle


【解决方案1】:

您正在 PL/SQL 上下文中运行所有三个查询(在匿名 PL/SQL 块内,beginend 之间),因此它们都需要遵循 PL/SQL 规则。

这意味着它们都需要被选择到某些东西中(或被视为游标),所以你需要一个日期变量来选择,然后你需要对该变量做一些事情:

declare
  x integer;
  d date;
begin
  select to_number(to_char(sysdate, 'hh24')) into x from dual;
  if x > 12 then
    select sysdate into d from dual;
  else
    select sysdate+1 into d from dual;
  end if;
  -- do something with the variable
  dbms_output.put_line(to_char(d, 'YYYY-MM-DD HH24:MI:SS'));
end;
/

请注意,我还更改了第一个查询以使用 hh24 格式元素,因为 hh 给出了 12 小时制时间,它永远不会超过 12。

你真的不需要第一个查询,你可以这样做:

declare
  d date;
begin
  if to_number(to_char(sysdate, 'hh24')) > 12 then
    select sysdate into d from dual;
...

但看起来您只使用 PL/SQL,因此您可以使用 if/then/else 构造,这在纯 SQL 中不可用。不过确实有 case,所以正如 @jarlh 所说,你可以这样做:

select
  case
    when to_number(to_char(sysdate,'hh24')) > 12
    then sysdate
    else sysdate + 1
  end as result
from dual;

或者

select
  case
    when extract(hour from systimestamp) > 12
...

您还保留了当前系统时间,即使您将日期更改为明天;你可能想将时间设置为午夜,您可以使用trunc(sysdate) 来完成。目前还不清楚你想要哪个。

逻辑看起来也很奇怪,但同样不清楚您的意图; 00-12 修改为明天,13-23 保留为今天,这可能是倒退的。如果您希望将中午之后(包括?)的任何时间视为明天,那么如果小时为 12 点或以上,您应该添加一天,因此 00-11 保留为今天,12-23 修改为明天。如果那是你的意思那么你可以这样做:

select case
  when extract(hour from systimestamp) >= 12
  then trunc(sysdate) + 1
  else trunc(sysdate)
  end as result
from dual;

或者更简单地说,假设您不想保留运行的实际时间,您可以执行以下操作:

select trunc(sysdate + 12/24) as result
from dual;

fiddle

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多