Using string in Oracle stored procedure

后端 未结 2 656
遥遥无期
遥遥无期 2021-01-27 00:56

When I simply write a query in which it has code like

Select * from ..
where ...
AND    gfcid in ( select regexp_substr(\'1005771621,1001035181\'||\',\',\'\\d+\'         


        
相关标签:
2条回答
  • 2021-01-27 01:35

    As far as I understand your problem, you need a method to accept a comma-delimited string as an input, break it into a collection of integers and then compare a number (read: integer) with the values in this collection.

    Oracle offers mainly three types of collections- varrays, nested tables and associative arrays. I would explain how to convert a comma-delimited string into a nested table and use it to query or compare.

    First, you need to define an object type in the schema. You can write queries using this type only if you define it at schema level.

    CREATE OR REPLACE TYPE entity_id AS OBJECT (id_val NUMBER(28));
    /
    
    CREATE OR REPLACE TYPE entity_id_set IS TABLE OF entity_id;
    /
    

    Next, define a function like this:

    FUNCTION comma_to_nt_integer (p_comma_delimited_str IN VARCHAR)
        RETURN entity_id_set IS
        v_table     entity_id_set;
    BEGIN
        WITH temp AS (SELECT TRIM(BOTH ',' FROM p_comma_delimited_str) AS str FROM DUAL)
            SELECT ENTITY_ID(TRIM (REGEXP_SUBSTR (t.str,
                                        '[^,]+',
                                        1,
                                        LEVEL)))
                       str
              BULK COLLECT INTO v_table
              FROM temp t
        CONNECT BY INSTR (str,
                          ',',
                          1,
                          LEVEL - 1) > 0;
    
        RETURN v_table;
    END comma_to_nt_integer;
    

    You are done with the DDL required for this task. Now, you can simply write your query as:

    SELECT *
      FROM ..  
     WHERE ...
           AND gfcid in (table(comma_to_nt_integer(GDFCID_STRING)));
    
    0 讨论(0)
  • 2021-01-27 01:36

    In general you can use

    execute immediate v_your_sql_code;

    to execute dynamic SQL within PL/SQL, but from your question I'm not really aware what you want to do.

    Edit:

    y_your_sql_code := 'Select yourColumn from ..  where ...AND  gfcid in ('||GDFCID_STRING||')';
    
    execute immediate v_your_sql_code into v_result;
    

    You'll have to define v_result in the right datatype, you could use more then one result variable if you need more result columns, you'll need i.e. a complex type if you can retrieve more than one row.

    0 讨论(0)
提交回复
热议问题