Using the “IN” clause with a comma delimited string from the output of a replace() function in Oracle SQL

前端 未结 5 921
逝去的感伤
逝去的感伤 2020-11-29 09:45

I have an comma delimited string which I want to use in an \"IN\" clause of the statement. eg: 100,101,102

Since In and \"IN\" clause I have to quote the individial

5条回答
  •  一个人的身影
    2020-11-29 10:32

    pure SQL, but not very well tested...

    select to_number(substr(postfix, 2, instr(postfix, ',' ,2)-2)) id 
      from (
           select substr(val, instr(val, ',', 1, n)) postfix 
             from (select ',101,102,103,' val from dual)
         , (
           select level n
             from dual 
          connect by level < 10) 
      where instr(val, ',', 1, n) > 0)
     where  instr(postfix, ',' ,2)> 2;
    

    EDIT: improved

    select substr(postfix, 1, instr(postfix, ',' ,1)-1)
      from (
           select substr(val, instr(val, ',',1, level)+1) postfix
             from (select ',101,102,103,' val from dual)
          connect by instr(val, ',', 2, level) > 0
      );
    

    Note:

    • pre/post fix your strings with comma
    • adopt the upper limit (10 in the example) as per your needs (not needed in the improved version).
    • use the in_list table function mentioned by Justing Cave, that's probably better :)

    credit: something like that is in Stephane Faroult's book "Refactorying SQL Applications" (O'Reilly)

提交回复
热议问题