Ashok kumar
Ashok kumar

Reputation: 1621

How to get comma separated values inside Oracle stored procedure

I have to pass FlightDate, FlightNumbers as parameters to Oracle Stored procedure like below.

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

I am not understanding how to convert FlightNumbers parameter to something like AND FlightNo IN ('0620,0712,0154') inside the query.

Upvotes: 0

Views: 6229

Answers (1)

Nick Krasnov
Nick Krasnov

Reputation: 27261

As one of the approaches, the regexp_substr() and regexp_count() regular expression functions can be used to split the source string into table rows and then you can easily include that result in your IN clause:

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

So, for instance, if you pass in FlightNumbers as '0620,0712,0154', the above query will produce the following result:

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

Having that at hand, your final query would be:

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);

Upvotes: 4

Related Questions