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
Use %ROWTYPE in that 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?
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);
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.