PL / pgSQL中的变量替换

时间:2010-11-30 07:09:43

标签: postgresql types plpgsql

我有一个select语句,它是根据提供的参数动态生成的。问题是postgresql总是说:

argument of WHERE must be type boolean, not type character varying无论参数是什么。我错过了什么吗?

CREATE OR REPLACE FUNCTION getuid(name character varying) RETURNS integer AS $$
    DECLARE 
        statement varchar;
        uid integer;
    BEGIN
        IF ($1 = '') THEN
            statement := 'TRUE';
            statement := CAST(statement AS BOOLEAN);
        ELSE
            statement := 'users.keywords ILIKE''' || '%' || $1 || '%''';
        END IF;
        SELECT INTO uid id FROM users WHERE "statement";
        RETURN uid;
    END;
$$ LANGUAGE plpgsql

2 个答案:

答案 0 :(得分:2)

如果要在函数内生成动态命令,则需要EXECUTE。您还可以使用两个不同的部分:

CREATE OR REPLACE FUNCTION getuid(name character varying) RETURNS integer AS $$
    DECLARE 
        statement varchar;
        uid integer;
    BEGIN
        IF ($1 = '' OR $1 IS NULL) THEN -- section 1
            SELECT id INTO uid FROM users;
        ELSE -- section 2
            SELECT id INTO uid FROM users WHERE users.keywords ILIKE '%' || $1 || '%';
        END IF;

        RETURN uid;
    END;
$$ LANGUAGE plpgsql;

答案 1 :(得分:0)

EXECUTE是PL / pgSQL语句而不是SQL语句。所以你必须将动态查询包装到PL / pgSQL存储过程中。

请注意变量替换,并且在构建查询时不要忘记使用quote_literal()quote_nullable()

请查看文档:{​​{3}}