PL/SQL query IN comma deliminated string

前端 未结 10 2125
攒了一身酷
攒了一身酷 2021-01-02 04:46

I am developing an application in Oracle APEX. I have a string with user id\'s that is comma deliminated which looks like this,

45,4932,20,19
相关标签:
10条回答
  • 2021-01-02 05:40

    As you are Storing User Ids as String so You can Easily match String Using Like as Below

    SELECT * FROM users u WHERE u.user_id LIKE '%'||(:P5_USER_ID_LIST)||'%'
    

    For Example

    :P5_USER_ID_LIST  = 45,4932,20,19
    

    Your Query Surely Will return Any of 1 User Id which Matches to Users table

    This Will Surely Resolve Your Issue , Enjoy

    0 讨论(0)
  • 2021-01-02 05:42

    If possible the best idea may be to not store your user ids in csv! Put them in a table or failing that an array etc. You cannot bind a csv field as a number.

    0 讨论(0)
  • 2021-01-02 05:45

    Create a native query rather than using "createQuery/createNamedQuery"

    0 讨论(0)
  • 2021-01-02 05:50

    The reason this is an issue is that you cannot just bind an in list the way you want, and just about everyone makes this mistake at least once as they are learning Oracle (and probably SQL!).

    When you bind the string '32,64,128', it effectively becomes a query like:

    select ...
    from t
    where t.c1 in ('32,64,128')
    

    To Oracle this is totally different to:

    select ...
    from t
    where t.c1 in (32,64,128)
    

    The first example has a single string value in the in list and the second has a 3 numbers in the in list. The reason you get an invalid number error is because Oracle attempts to cast the string '32,64,128' into a number, which it cannot do due to the commas in the string.

    A variation of this "how do I bind an in list" question has come up on here quite a few times recently.

    Generically, and without resorting to any PLSQL, worrying about SQL Injection or not binding the query correctly, you can use this trick:

    with bound_inlist
      as
      (
      select
        substr(txt,
               instr (txt, ',', 1, level  ) + 1,
               instr (txt, ',', 1, level+1) - instr (txt, ',', 1, level) -1 )
               as token
        from (select ','||:txt||',' txt from dual)
      connect by level <= length(:txt)-length(replace(:txt,',',''))+1
      )
      select *
    from bound_inlist a, users u
    where a.token = u.id;
    
    0 讨论(0)
提交回复
热议问题