Wednesday, February 7, 2018

Oracle query to display the string with comma separated value as query row results. With no use of Table creation


There was a situation in my project where query for set of data (result of the query will provide one field with different value)

For example,
Employee table, and fetch only the employee last name.

Now i wanted to test an fix in the application code, where the query was present in the properties file.
Properties file had

query.employee=select distinct employee_firstName from Employee
There was no logical change in code. For testing i need to provide the query with constant values.

For example, for customer name i had data like below

   john1,john2,john3

SELECT REGEXP_SUBSTR (
         'john1,john2,john3',
         '[^,]+',
         1,
         LEVEL)
         val
FROM DUAL
CONNECT BY REGEXP_SUBSTR (
             'jonh1,jonh2,jonh3',
             '[^,]+',
             1,
             LEVEL)
             IS NOT NULL;
The result of the above query will be a Row of values.

john1
john2
john3

Comma separated string transformed to a column of data, without any table.

The RegExp_substr function in oracle has a size limitation if we use more than certain values.
so in that case i was about to use union

SELECT REGEXP_SUBSTR ('1,2,3','[^,]+',1,LEVEL)val FROM DUAL CONNECT BY REGEXP_SUBSTR ( '1,2,3', '[^,]+', 1, LEVEL) IS NOT NULL
union
SELECT REGEXP_SUBSTR ('4,5,6','[^,]+',1,LEVEL)val FROM DUAL CONNECT BY REGEXP_SUBSTR ( '4,5,6', '[^,]+', 1, LEVEL) IS NOT NULL
union
SELECT REGEXP_SUBSTR ('7,8,9','[^,]+',1,LEVEL)val FROM DUAL CONNECT BY REGEXP_SUBSTR ( '7,8,9', '[^,]+', 1, LEVEL) IS NOT NULL
Result of the above query is
1
2
3
4
5
6
7
8
9

There are other ways of achieving this result, in my case i had around 1000 string with comma separated values. For a quick turnaround time the above approach worked.

we can use With query for the same too.









No comments:

Post a Comment