PL/SQL query IN comma deliminated string

前端 未结 10 2126
攒了一身酷
攒了一身酷 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: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;
    

提交回复
热议问题