如何在Oracle存储过程中获取逗号分隔值

时间:2013-07-23 04:43:35

标签: oracle csv oracle11g oracle-sqldeveloper

我必须将FlightDateFlightNumbers作为参数传递给Oracle存储过程,如下所示。

CREATE OR REPLACE PROCEDURE GetPaxDetails(
   FlyingDate IN PAX_DETAILS.FlightDate%TYPE, 
   FlightNumbers IN VARCHAR(300))
IS
BEGIN
    -- Assume that we've received **FlightNumbers** as '0620,0712,0154'
    -- Basically I am trying to select all passenger details (PAX_DETAILS) 
    -- for those flights passed in as a parameter(**FlightNumbers**) 
    -- for the specified dates
    -- In this procedure the query should be generated something like below:
    SELECT * 
      FROM PAX_DETAILS 
     WHERE TO_DATE(FlightDate,'DDMONYY') BETWEEN TO_DATE(FlyingDate,'DDMONYY') 
                                             AND TO_DATE(FlyingDate,'DDMONYY') + 1 
       AND FlightNo IN ('0620,0712,0154')

END

我不了解如何在查询中将FlightNumbers参数转换为AND FlightNo IN ('0620,0712,0154')之类的内容。

1 个答案:

答案 0 :(得分:4)

作为其中一种方法,regexp_substr()regexp_count()正则表达式函数可用于将源字符串拆分为表格行,然后您可以轻松地将该结果包含在IN中子句:

-- splitting a comma separated string
select regexp_substr(FlightNumbers, '[^,]+', 1, level) as num
  from dual
connect by level <= regexp_count(FlightNumbers, '[^,]+')

因此,例如,如果您将FlightNumbers传递为“0620,0712,0154”,则上述查询将产生以下结果:

NUM
--------
0620
0712
0154

有了这个,你的最终查询将是:

with numbers(num) as(
   select regexp_substr(FlightNumbers, '[^,]+', 1, level) as num
     from dual
  connect by level <= regexp_count(FlightNumbers , '[^,]+')
 )
SELECT *           -- do not forget INTO clause
  FROM PAX_DETAILS 
 WHERE TO_DATE(FlightDate,'DDMONYY') BETWEEN TO_DATE(FlyingDate,'DDMONYY') 
                                         AND TO_DATE(FlyingDate,'DDMONYY') + 1 
   AND FlightNo IN (select num
                      from numbers);