2

I am trying to assign a variable the result of a query in a postgres stored procedure. Here is what I am trying to run:

CREATE OR Replace PROCEDURE schema.MyProcedure() 
AS $$

DECLARE 
    RowCount int = 100;
    
BEGIN
    
    select cnt into RowCount 
    from (
        Select count(*) as cnt
        From schema.MyTable
        ) ;
    
    RAISE NOTICE 'RowCount: %', RowCount;
    
END;
$$
LANGUAGE plpgsql;

schema.MyTable is just some arbitrary table name but the script is not displaying anything, not even the random value I assigned RowCount to (100).

What am I doing wrong?

Thanks

3
  • You either either need to use an inout parameter to return the value, or use a function instead of a procedure to return a value. Commented Sep 24, 2021 at 18:22
  • I dont need the RowCount returned, I was just using Raise Notice to check if the true table's row count was being assigned to the RowCount variable. Commented Sep 24, 2021 at 18:27
  • 1
    Works for me, though I did have to add an alias for the subquery: ...From schema.MyTable) as ct, to CREATE the procedure. call myprocedure (); NOTICE: RowCount: 68. Also I would avoid using mixed case identifiers. Best guess is you are not calling the procedure you think you are. Commented Sep 24, 2021 at 18:27

2 Answers 2

2

You need an alias for the subquery, for example : as sub

CREATE OR Replace PROCEDURE schema.MyProcedure() 
AS $$

DECLARE 
    RowCount int = 100;
    
BEGIN
    
    select cnt into RowCount 
    from (
        Select count(*) as cnt
        From schema.MyTable
        ) as sub ;
    
    RAISE NOTICE 'RowCount: %', RowCount;
    
END;
$$
LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

1 Comment

Though it could be simplified to: Select count(*) into RowCount from ... and eliminate the sub query.
1

You can also assign any variable with a query result in parenthesis.

CREATE OR REPLACE PROCEDURE schema.my_procedure()
AS
$$
DECLARE
    row_count BIGINT;
BEGIN

    row_count = (SELECT COUNT(*) FROM schema.my_table);

    RAISE NOTICE 'RowCount: %', row_count;

END;
$$ LANGUAGE plpgsql;

You should use BIGINT instead of INT.

And it's far better to write your code and table definition with snake_case style as possible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.