【问题标题】:pl/sql for loop with select statement using variable make wrong result?pl/sql for 循环与使用变量的 select 语句会产生错误的结果?
【发布时间】:2017-11-09 09:55:16
【问题描述】:

我在select语句中使用了变量city_no,但是我发现使用直接值和变量city_no的结果不同> 甚至他们的价值观也是一样的。当我使用直接值'020'时输出为377,当我使用变量时输出为16。我不知道为什么会有所不同,或者我的选择语句有什么问题?下面是sql代码:

    city_no:='020';
    need_kinds := 0;
    for need_item in (select n.rootcode, n.need2018, n.got2018
                        from jq_temp_hy_need_2018 n
                       where n.city_no = city_no
                         and (n.need2018 - n.got2018) > 0) loop
      current_need_map(need_item.rootcode) := need_item.need2018 -
                                              need_item.got2018;
      already_get_map(need_item.rootcode) := need_item.got2018;
      need_kinds:=need_kinds+1;
    end loop;
    -- out put 377
   dbms_output.put_line(need_kinds);

当我将 select 语句的条件改为 n.city_no = '020' 时,输出值变成了 16,实际上我知道 n.city_no 时 count(1) 是 16 = '020'

    city_no:='020';
    need_kinds := 0;
    for need_item in (select n.rootcode, n.need2018, n.got2018
                        from jq_temp_hy_need_2018 n
                       where n.city_no = '020'
                         and (n.need2018 - n.got2018) > 0) loop
      current_need_map(need_item.rootcode) := need_item.need2018 -
                                              need_item.got2018;
      already_get_map(need_item.rootcode) := need_item.got2018;
      need_kinds:=need_kinds+1;
    end loop;
    -- out put 16
    dbms_output.put_line(need_kinds);

【问题讨论】:

    标签: oracle variables for-loop select plsql


    【解决方案1】:

    您的变量名与表中的列名相同,因此使用该列代替您的 select 语句中的变量。

    将您的变量重命名为独特的名称以解决问题。

    【讨论】:

      【解决方案2】:

      当值为NULL 或隐式转换时,您可能会遇到问题。

      您应该尝试使用TO_CHAR 投射两边,并使用NVL

      -- change your where condition to this:
      where TO_CHAR( NVL(n.city_no, '#@') ) = TO_CHAR(city_no)
      

      【讨论】:

      • 当我将条件更改为您的条件时它仍然输出377,并且colum city_no类型是VARCHAR2(16)并且不为null
      猜你喜欢
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 2018-12-09
      • 1970-01-01
      相关资源
      最近更新 更多