ingres

Ingres stored procedure to delete multiple records from table


I am creating a SP in Ingres to delete multiple records from single table by comma separated id's, but it is not working. Though when I execute it in a separate query (without storedprocedure) then it is deleting records.

create procedure sptest
(
    In Ids varchar(300)
)
AS
BEGIN
   Delete from "ingres".mytable where request_id IN (:Ids);

END

Requested rows should be deleted from table


Solution

  • The input is a varchar so in effect what you have in the delete statement is something like:

    delete from mytable where request_id in ('1,2,3,4');

    Inside a database procedure you can't run "execute immediate", so you can't build a delete string without the quotes and execute it dynamically (though this might be an option to you if your calling program has "execute immediate" available).

    To process the IN list within a database procedure I think you'll need to loop through the input string and delete for each value... eg:

    set session authorization ingres;
    
    drop table if exists mytable;
    create table mytable(request_id integer);
    insert into mytable values(1),(2),(5),(10);
    
    drop procedure if exists sptest;
    create procedure sptest
    (
        In Ids varchar(300)
    )
    AS
    declare msg = varchar(300) not null;
            eno = integer not null;
            rc  = integer not null;
            pos = integer not null;
            n   = varchar(300);
    BEGIN
       while (length(:Ids) > 0)
       do
         pos = locate(:Ids, ',');
         n = left(:Ids, :pos-1);
         Ids = shift(:Ids, -1 * pos);
         msg = 'Removing ' + :n;
         message :msg;
         Delete from "ingres".mytable where request_id = integer(:n);
         select iierrornumber, iirowcount into :eno, :rc;
         msg = 'Error number '+varchar(:eno) + ' rowcount ' + varchar(:rc);
         message :msg;
       endwhile;
    END;
    
    execute procedure sptest('1,5,10');
    select * from mytable;