Search code examples
sqlarraysdb2-400rpgle

How to pass Array to SQL Stored Procedure


I am trying to pass arrays to a DB2 stored procedure and I am having trouble.

Here are a few code snippets:

create type intArrayType as integer array[];

CREATE OR REPLACE PROCEDURE
array_trial (IN integer_array INTARRAYTYPE)

BEGIN
  SELECT UNNEST(integer_array) FROM sysibm.sysdummy1;
END 

It compiles, but when I try to call:

CALL array_trial(ARRAY[1,2,3]);

I am getting a -104 error.

When I try to call from RPGLE, I cannot compile because it does not like the array

Any ideas?


Solution

  • UNNEST is used in the from clause as it creates a temporary table...

    CREATE OR REPLACE PROCEDURE
    array_trial (IN integer_array INTARRAYTYPE)
    
    BEGIN
      declare c1 cursor with return to client for 
         SELECT * FROM UNNEST(integer_array) as rs;
      open c1;
    END;
    

    Unfortunately, the ARRAY constructor is currently rather limited. The documentation specifically says can only be specified on the right side of a SET variable or assignment-statement. So trying to use it directly like so doesn't work.

    CALL array_trial(ARRAY[1,2,3]);
    

    It returns the following message:

    SQL State: 428H2
    Vendor Code: -20441
    Message: [SQ20441] Array type not valid where specified. 
    Cause . . . . . :   An array type was used but is not allowed in the 
    specified context.  Array types can only be used: -- As an argument of an 
    SQL or JAVA procedure. -- For an SQL variable declared in an SQL procedure.
    -- In a CAST specification in an SQL procedure. 
    Recovery  . . . :   Remove the reference to the array type. Try the request again.
    

    You can build a driver stored procedure:

    create or replace procedure mysp
    begin
      declare myarray intArrayType;
      set myarray = ARRAY[1,2,3];
      call array_trial(myarray);
    end;
    

    And call that

    call mysp;
    

    From what I've been able to find so far An SP with an array parm can be called directly from another SQL procedure or Java...but not RPGLE.