简体   繁体   中英

Reference variable in PL/pgSQL function

I have a function and inside that function I create variables. I want to use the created variable as a threshold for filtering.

CREATE OR REPLACE FUNCTION someF(a integer, b integer, c integer)
RETURNS void AS
$$
DECLARE
    problematicVariable float := $1 / $2;

BEGIN
    FOR i in 1 .. $3:
    CREATE TABLE IF NOT EXISTS someTable AS
        SELECT someFunction( 
            'SELECT id, 
            FROM yetAnotherTable st 
            WHERE st.agg <= problematicVariable')
    END LOOP;
END
$$
language 'plpgsql';

However, I get the error that:

 ERROR: column "problematicVariable" does not exist 

How would I tell postgres that this is not a column but a variable I created within the function body?

The issue is that the name problematicVariable is interpreted in someFunction() , where it is obviously not defined. Since that is a stable call (the function parameter is always the same so the same data would return from the function on every call, assuming no dependency on volatile values) you are better off taking that out of the loop and calling someF() repeatedly with the result of that first function call.

CREATE OR REPLACE FUNCTION someF(a integer, b integer, c integer) RETURNS someType AS $$
DECLARE
    problematicVariable float := $1 / $2;
    idVar someType;
BEGIN
    SELECT id INTO idVar 
    FROM yetAnotherTable st 
    WHERE st.agg <= problematicVariable;

    FOR i IN 1 .. $3 LOOP
        CREATE TABLE IF NOT EXISTS someTable AS
            SELECT someFunction(idVar);
    END LOOP;
END;
$$ LANGUAGE plpgsql;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM