Using variables from parent in nested postgresql function?

时间:2018-02-01 18:08:47

标签: sql postgresql

I'm have a pretty long SQL routine that gets a few parameters and runs through a whole bunch of CASE statements. I have the following structure:

DO $$
DECLARE var INTEGER = "someColumn" FROM TABLE LIMIT 1;

BEGIN;

CREATE OR REPLACE FUNCTION pg_temp.fn(var2 boolean) returns decimal AS 
$fn$ SELECT CASE WHEN var2 THEN var::decimal ELSE 0::decimal END $fn$ language sql;
$$

And using var inside of fn does not seem to quite work. As in the column does not exist. Is there a way to make it work, am I maybe thinking too complicated?

Edit: fixed the type that was missing. In the original code there is a type declaration, the declaration is not the problem. Using the variable in the nested function is.

1 个答案:

答案 0 :(得分:1)

First of all. THIS IS NOT THE BEST PRACTICE. It can be done, but it is not recommended to use nested functions.

The problem is that var is in a different scope than the function. You have to "write" the function as an independent unit. You can do this with EXECUTE and FORMAT.

Here is an example of a function that shows var as a message:

DO $$
DECLARE
    sql text; -- To "write" the function
    var integer := id FROM table_name ORDER BY id LIMIT 1;
BEGIN
-- To make it hapend I use $test$ to set the function.
-- FORMAT is to allocate var into the function through '%s'.
-- you have to use the correct sintax acording to the data type.
    sql :=  FORMAT($test$
CREATE OR REPLACE FUNCTION test() RETURNS void AS $FUNCTION$
BEGIN
    RAISE NOTICE '%s';
END; $FUNCTION$ LANGUAGE plpgsql
$test$,var);
    EXECUTE sql;
END; $$