I have a string which has list of valid places.
var locations = COLOMBO,DELHI,SINGAPORE
I want to query all the employees belonging to the location mention in the above string
I am using the following query
SELECT emp_id,emp_name
FROM EMPLOYEE
WHERE emp_location IN (locations) ;
Oracle is considering it as single string and searching for the below query string
SELECT emp_id,emp_name
FROM EMPLOYEE
WHERE emp_location IN ('COLOMBO,DELHI,SINGAPORE');
I want to know if there is any way I can pass the string and get the valid emp_id
, emp_name
belonging to the location mentioned in the string.
As mentioned here
First you need to use the REGEXP_SUBSTR
function to split the string into individual strings
VAR locations = 'COLOMBO,DELHI,SINGAPORE';
SELECT REGEXP_SUBSTR(locations,'[^,]+', 1, level)
FROM dual
CONNECT BY REGEXP_SUBSTR(locations, '[^,]+', 1, level) IS NOT NULL;
Then use it as a sub query in a select to get the desired result
VAR locations = 'COLOMBO,DELHI,SINGAPORE';
SELECT emp_id,emp_name FROM EMPLOYEE
WHERE emp_location in(
SELECT REGEXP_SUBSTR(locations,'[^,]+', 1, level) FROM dual
CONNECT BY REGEXP_SUBSTR(locations, '[^,]+', 1, level) IS NOT NULL);
You are looking for locations mentioned in the string, so actually for locations that are a substring of your string. Oracle offers INSTR for such a search.
Only be aware to look for complete cities from comma to comma (add commas in front and end). So not to find 'YORK' in 'LONDON,NEW YORK' (for ',YORK,' is not a substring of ',LONDON,NEW YORK,' wheras 'YORK' without commas would be a substring of 'LONDON,NEW YORK').
select emp_id,emp_name
from EMPLOYEE
where instr(','|| locations || ',' , ',' || emp_location || ',') > 0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.