首页 > 解决方案 > 在 oracle 中迭代一组 varchar2 的选择查询

问题描述

我有以下选择查询

    select * from BUSINESS_T
where  store_code = '075'
and item_no in
(
         select item_no from BUSINESS_T a
         where store_code = '075'
         and exists
         (
                  select * from BUSINESS_T
                  where store_code = a.store_code 
                  and item_no = a.item_no
                  and
                  (
                            VALID_FROM_DTIME between a.VALID_FROM_DTIME and a.VALID_TO_DTIME
                            or VALID_TO_DTIME between a.VALID_FROM_DTIME and a.VALID_TO_DTIME
                            or (VALID_FROM_DTIME > a.VALID_FROM_DTIME and a.VALID_TO_DTIME is null)
                            or (VALID_FROM_DTIME < a.VALID_FROM_DTIME and VALID_TO_DTIME is null)
                  )
                  and del_dtime is null
                  and not
                  (
                            a.rowid = rowid
                  )
         )
)
order by item_no, VALID_FROM_DTIME

需要为商店编号数组运行它 {'071','072','073','074','075','076'} 这个数组应该在查询本身内部定义。

那里有近 400 多个固定商店号码。必须为每个商店运行上述查询,一次为一个商店运行,以查找该特定商店中的重叠

标签: oracleloops

解决方案


使用in

select *
from business_t
where 
    class_unit_code in ('071', '072', '073', '074', '075', '076')
    and b_type = 'CASH_AND_CARRY' 
    and delete_date is null

对于这个特定的字符串值序列,我们可能会尝试使用正则表达式来缩短谓词(尽管这可能效率较低):

regexp_like(class_unit_code, '^07[1-6]$')

或者,如果字符串总是包含数值,我们可以转换并使用范围比较(这也没有第一个选项那么有效 - 在这种情况下,应该使用数字数据类型创建列):

to_number(class_unit_code) between 71 and 76

推荐阅读