简体   繁体   中英

Oracle use a string inside IN condition

I have a select statement where I use the IN condition, and inside the IN condition I have a string...how can I ignore the single quotes?

Select * from employ where id = 12 and org_id in ({$id})
$id = '12,13'

Thanks

in is used with collections , so your input string first should be converted into collection (by breaking into rows, based on comma delimiter)

Try something like this

Select * from employ where id = 12 and org_id in (
SELECT decode(:input_id,null,  (select  employ.org_id from dual) 
,TRIM(REGEXP_SUBSTR(temp, '[^,]+', 1, level)) )  
    FROM (SELECT  :input_id temp FROM DUAL)
    CONNECT BY level <= REGEXP_COUNT(temp, '[^,]+')
    )

by the way, this org_id in () will return true if :input_id is null .

Another approach would be to construct the whole query as a string first and then execute it either with execute immediate or through php . However this could raise sql injection concerns.

I am guessing that you want to process a list. Unfortunately, SQL doesn't allow a parameter to be a list, so you have to do more work.

One method uses like (or a regular expression):

Select *
from employ
where id = 12 and
      ',' || org_id || ',' like '%,' || {$id} || ',%';

If performance is an issue and you want to use indexes, you may need to investigate other options. The simplest is to dispense with the parameter and just modify the query string (using dynamic SQL to execute the query).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM