DEV Community

Bruno Panassi
Bruno Panassi

Posted on

8 1

Using an Array of strings in a query with Oracle PL/SQL

oracle-database

Oracle Function

In this case we will use a function created in Oracle PL/SQL that receives a string value and return as an array to your query:



CREATE OR REPLACE FUNCTION string_to_list (stringParameter IN VARCHAR2,separator IN VARCHAR2 DEFAULT ',')
   RETURN ARRAY_TABLE
AS
   stringValue      LONG DEFAULT stringParameter || separator;
   dataToReturn     ARRAY_TABLE := ARRAY_TABLE ();
   n                NUMBER;
BEGIN
   LOOP
      EXIT WHEN stringValue IS NULL;
      n                                 := INSTR (stringValue, separator);
      dataToReturn.EXTEND;
      dataToReturn (dataToReturn.COUNT) := LTRIM (RTRIM (SUBSTR (stringValue, 1, n - 1)));
      stringValue                       := SUBSTR (stringValue, n + 1);
   EN


Enter fullscreen mode Exit fullscreen mode

You can see that the return is a type of ARRAY TABLE, this type can be created in this way:



CREATE TYPE "ARRAY_TABLE" as table
     of varchar2 (4210)


Enter fullscreen mode Exit fullscreen mode

So with this type and function created, you can use your query like this:



SELECT * FROM TABLE_TO_SEARCH
WHERE (upper(column_to_search) in (SELECT * FROM TABLE(IN_LIST(upper(:stringParameter)))))


Enter fullscreen mode Exit fullscreen mode

Where the stringParameter it's a value like:

  • "Value 1, Value 2, Value 3".

The stringParameter is written with ":" because in this case i used the Dbeaver tool.

Sorry for the Queries shown above for not being indented and with the usual colors.
I hope that this can help you like it helped me.

Thanks for reading.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay