I'm using Oracle 8i. I have three tables: One table has a numeric column which contains one number. We'll call it A.Col_1. A second table has a varchar2 column which contains a comma delimited list of numbers. We'll call it B.Col_2. In my query, I need to do a WHERE IN clause WHERE A.Col_1 IN B.Col_2. But this does not work. How can I do this?
Since your second table has a list of comma delimited numbers, then you'll have to parse each number from that list to see if that column contains the number you are looking for. You'll have to do this using built SQL functions. The INSTR function will tell you where a string lies within another string. The SUBSTR function will return a substring of a string. So, I want to see if my column contains the entire number I am looking for and not just a portion of the number. For instance, if I am looking for the number '123', then I don't want a true result if the number is really '1234'. So something like the following is a start to your solution:
SELECT * FROM A,B WHERE INSTR(a.col_1,b.col_2) > 0 AND SUBSTR(INSTR(a.col_1,b.col_2),1,1)=',') AND SUBSTR(INSTR(a.col_1,b.col_2)+LENGTH(a.col_1),1,1)=',');If your SQL query starts to get too complicated, then you'll have to resort to parsing with PL/SQL.
For More Information
- Dozens more answers to tough Oracle questions from Brian Peasland are available.
- The Best Oracle Web Links: tips, tutorials, scripts, and more.
- Have an Oracle or SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical Oracle and SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.