PLPGSQL returning number of rows

Started by Patrick Bover 9 years ago2 messagesgeneral
Jump to latest
#1Patrick B
patrickbakerbr@gmail.com

Hi guys,

I'm writing a simple Plpgsql function to delete some data from different
tables.

The function starts with a select, and then 2 deletes after that.

How can I return the number of rows that each delete performed?

CREATE or REPLACE FUNCTION delete_ids_clientid(account_id integer)

RETURNS integer AS $$

declare

row record;

account_id integer;

BEGIN

FOR row IN EXECUTE '

SELECT

t1.id

FROM

public.table2 t2

JOIN

public.table1 t1 ON t2.id = t1.id

WHERE

t2.account_id = ' || account_id || ''

LOOP

DELETE FROM public.table1 WHERE id IN

(

SELECT

id

FROM

public.table1 t1

WHERE

t1.id = row.id

);

DELETE FROM public.table2 WHERE billable_id IN

(

SELECT

billable_id

FROM

public.table2 t1

WHERE

t1.id = row.id

);

END LOOP;

END

$$ language 'plpgsql';

Cheers

#2David G. Johnston
david.g.johnston@gmail.com
In reply to: Patrick B (#1)
Re: PLPGSQL returning number of rows

On Thu, Nov 10, 2016 at 5:44 PM, Patrick B <patrickbakerbr@gmail.com> wrote:

Hi guys,

I'm writing a simple Plpgsql function to delete some data from different
tables.

The function starts with a select, and then 2 deletes after that.

How can I return the number of rows that each delete performed?

​The pl/pgsql chapter named: "Basic Statements - Obtaining the Result
Status" sounds like a good place to look...

Here's a link:

https://www.postgresql.org/docs/9.6/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-DIAGNOSTICS

​David J.