You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

计算行程最大最小值报PLS-00302: MIN未声明错误如何解决

问题原因
  • 核心错误是你混淆了聚合函数的使用场景和行类型变量的用法:
    • MIN()/MAX()是SQL聚合函数,需要在SELECT查询语句中执行,不能作为PL/SQL行类型变量(你代码里的distance_row)的属性调用,distance_row.min(distance)这种写法是非法的,Oracle会把min当成distance_row的一个字段来识别,自然会报“未声明”错误。
    • 你的游标逻辑本身也不符合需求:游标查询的WHERE条件限定了distance = p_distance,查询结果所有行的距离都等于传入的参数,就算你写法正确也不可能得到整个表的最大、最小距离。
修正方案

给你一个符合需求的写法示例,先查询全局最大、最小距离,再遍历输出匹配的行程:

create or replace procedure longandshortdist 
is
  -- 声明变量存全局最大、最小距离
  v_min_dist distances.distance%type;
  v_max_dist distances.distance%type;
  cursor longshortcursor is 
    select source_town, destination_town, distance
    from distances;
  distance_row longshortcursor%rowtype;
begin
  -- 先查询得到全局的最大最小距离
  select min(distance), max(distance) into v_min_dist, v_max_dist
  from distances;

  for distance_row in longshortcursor
  loop
    dbms_output.put_line('出发城市: ' || distance_row.source_town 
    || ' 到达城市: ' || distance_row.destination_town 
    || ' 全程最短距离: ' || v_min_dist 
    || ' 全程最长距离: ' || v_max_dist);
  end loop;
end;
/

如果你的需求是按出发+到达城市分组,计算每组的最大最小距离,可以直接在游标里做聚合查询,不用单独查变量:

create or replace procedure longandshortdist 
is
  cursor longshortcursor is 
    select source_town, destination_town, 
           min(distance) as min_dist, 
           max(distance) as max_dist
    from distances
    group by source_town, destination_town;
  distance_row longshortcursor%rowtype;
begin
  for distance_row in longshortcursor
  loop
    dbms_output.put_line('出发城市: ' || distance_row.source_town 
    || ' 到达城市: ' || distance_row.destination_town 
    || ' 该线路最短距离: ' || distance_row.min_dist 
    || ' 该线路最长距离: ' || distance_row.max_dist);
  end loop;
end;
/

内容的提问来源于stack exchange,提问作者Mohammad Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:54:07