问题
This question already has an answer here:
- PL/SQL - Use “List” Variable in Where In Clause 3 answers
- How to load a large number of strings to match with oracle database? 3 answers
- WHERE IN condition not accepting String value 4 answers
Below is my query and i am passing a string value 1,2 as bind value but it is showing an error as it is not a valid number. I know IN accepts only number but here i need to pass the string value
SELECT e.*
FROM employee_detail e
WHERE e.emp_id IN (:emp_id)
回答1:
You can use string comparisons instead of an IN condition.
select ...
from ...
where ',' || :emp_id || ',' like '%,' || to_char(emp_id) || ',%'
;
回答2:
In
is used with list of values
or subqueries
.
You can convert a comma separeted string
into a subquery
, by using the following hack:
SELECT TRIM(REGEXP_SUBSTR(temp, '[^,]+', 1, level))
FROM (SELECT :emp_id temp FROM DUAL)
CONNECT BY level <= REGEXP_COUNT(temp, '[^,]+')
Here the 1,2,3
sting will be converted into subquery
that returns 3
rows.
So, the end result, for your case, could be something like this:
SELECT e.*
FROM employee_detail e
WHERE e.emp_id in (
SELECT decode(:emp_id,null, (select e.emp_id from dual)
,TRIM(REGEXP_SUBSTR(temp, '[^,]+', 1, level)) )
FROM (SELECT :emp_id temp FROM DUAL)
CONNECT BY level <= REGEXP_COUNT(temp, '[^,]+'))
Note that in this case In
will return true
if :emp_id
is null
and this was deliberatly achieved by using decode
function.
来源:https://stackoverflow.com/questions/44778342/unable-to-pass-string-value-1-2-as-input-to-an-oracle-query