Declare variable of composite type in PostgreSQL using %TYPE

后端 未结 1 1235
眼角桃花
眼角桃花 2021-01-21 21:09

Question: How can I declare a variable of the same type a parameter in a stored function?

The simple answer is use %TYPE, this works:

CREATE         


        
相关标签:
1条回答
  • 2021-01-21 21:23

    Use %ROWTYPE in that case.

    Edit - simple case

    Tests by A.H. and DavidEG have shown this won't work. Interesting problem!
    You could try a workaround. As long as your definition is like the example you can simply resort to

    CREATE FUNCTION test(param1 comp_type)
      RETURNS integer AS
    $BODY$ 
    DECLARE
        myvar comp_type;
    BEGIN
        return 1;
    END;
    $BODY$
      LANGUAGE plpgsql VOLATILE;
    

    But your real problem is probably not as simple as that?

    Edit 2 - the real problem

    As expected, the real problem is more complex: a polymorphic input type.
    Workaround for that scenario was harder, but should work flawlessly:

    CREATE FUNCTION test(param1 anyelement, OUT a integer, OUT myvar anyelement)
      RETURNS record AS
    $BODY$
    BEGIN
        myvar := $1;  -- myvar has now the required type.
    
        --- do stuff with myvar.
    
        myvar := NULL;  -- reset if you don't want to output ..
        a := 1;
    END;
    $BODY$
      LANGUAGE plpgsql VOLATILE;
    

    Call:

    SELECT a FROM test('("foo")'::comp_type); -- just retrieve a, ignore myvar
    

    See full output:

    SELECT * FROM test('("foo")'::comp_type);
    

    Note for PostgreSQL 9.0+

    There has been a crucial update in v9.0. I quote the release notes:

    • Allow input parameters to be assigned values within PL/pgSQL functions (Steve Prentice)

    Formerly, input parameters were treated as being declared CONST, so the function's code could not change their values. This restriction has been removed to simplify porting of functions from other DBMSes that do not impose the equivalent restriction. An input parameter now acts like a local variable initialized to the passed-in value.

    Ergo, in addition to my workaround, you can utilize input variables directly.

    Dynamic Filed names

    • How to clone a RECORD in PostgreSQL
    • How to set value of composite variable field using dynamic SQL
    0 讨论(0)
提交回复
热议问题