Count the rows affected by plpgsql function

前端 未结 1 1942
北荒
北荒 2020-12-12 04:15

I have the following function:

CREATE FUNCTION user_delete(IN id INT4)
  RETURNS VOID
AS
  $BODY$
  BEGIN
    SELECT * FROM \"user\" WHERE user_id = id FOR U         


        
相关标签:
1条回答
  • 2020-12-12 05:00

    You can use:

    GET DIAGNOSTICS integer_var = ROW_COUNT;
    

    .. and let the function return the count. Details in the manual.

    Example:

    CREATE OR REPLACE FUNCTION user_delete(id int, OUT del_ct int) AS
    $func$
    DECLARE
       i int;  -- helper var
    BEGIN
       DELETE FROM user_role WHERE user_id = $1;
       GET DIAGNOSTICS del_ct = ROW_COUNT;  -- init
    
       DELETE FROM user_permission WHERE user_id = $1;
       GET DIAGNOSTICS i = ROW_COUNT;  del_ct := del_ct + i;
    
       DELETE FROM permission_cache WHERE user_id = $1;
       GET DIAGNOSTICS i = ROW_COUNT;  del_ct := del_ct + i;
    
       DELETE FROM access WHERE user_id = $1;
       GET DIAGNOSTICS i = ROW_COUNT;  del_ct := del_ct + i;
    
       DELETE FROM "user" WHERE user_id = $1;
       GET DIAGNOSTICS i = ROW_COUNT;  del_ct := del_ct + i;
    END
    $func$  LANGUAGE plpgsql;
    

    You had this as 1st statement:

    SELECT * FROM "user" WHERE user_id = $1 FOR UPDATE;

    Invalid syntax - inside a plpgsql function you need to use PERFORM for SELECT statements without target:

    PERFORM * FROM "user" WHERE user_id = $1 FOR UPDATE;
    
    • SELECT raises exception in PL/pgSQL function

    But the ensuing DELETE statement locks the row just as well. No need for manual locking with FOR UPDATE to begin with.

    The added OUT del_ct int declares an OUT parameter that can be assigned like any variable and is returned at the end of the function automatically. It also obviates the need for an explicit RETURNS declaration.

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