2

我似乎找不到将查询作为参数传递给我的 sql 函数的方法。我的问题是表“my_employees1”可能是动态的。

DROP FUNCTION function_test(text);
CREATE OR REPLACE FUNCTION function_test(text) RETURNS bigint AS '
    DECLARE ret bigint;
    BEGIN 
        SELECT count(mt.id) INTO ret
    FROM mytable as mt
    WHERE mt.location_id = 29671
    --and mt.employee_id in (SELECT id from my_employees1);
    --and mt.employee_id in ($1);
    $1;
    RETURN ret;
    END;
' LANGUAGE plpgsql;

select function_test('and mt.employee_id in (SELECT id from my_employees1)');
select function_test('SELECT id from my_employees1');
4

1 回答 1

0

它必须是动态构建的:

DROP FUNCTION function_test(text);
CREATE OR REPLACE FUNCTION function_test(text) RETURNS bigint AS $$
    DECLARE
        ret bigint;
    BEGIN
    execute(format($q$
        SELECT count(mt.id) INTO ret
        FROM mytable as mt
        WHERE mt.location_id = 29671
        %s; $q$, $1)
    );
    RETURN ret;
    END;
$$ LANGUAGE plpgsql;

和是美元报价$$$q$只要内部标识符不同,它们就可以嵌套。除了允许使用不带引号的引号和可嵌套的明显优势之外,它还可以让语法高亮发挥作用。

于 2012-10-24T17:46:45.437 回答