postgresql查询中不存在类型EXECUTE

时间:2013-12-17 03:32:44

标签: sql function postgresql plpgsql dynamic-sql

我正在尝试创建以下功能。功能已成功创建,但在尝试调用它时抛出错误

  

类型EXECUTE不存在!

CREATE OR REPLACE FUNCTION exa(ids text, length integer, fields text)  returns text AS
$BODY$
DECLARE
    chars INT[] := string_to_array(ids, ',');
    result text := '';
    i integer := 0;
    temp text := '';
BEGIN

    for i in 1..length loop
        temp := EXECUTE 'SELECT ' || fields || ' from user_index where userid=' || chars[i];
            result := result || temp;
        IF i < length THEN
            result := result || ',';    
        END IF;
    end loop;
    return result;
END
$BODY$ language plpgsql;

1 个答案:

答案 0 :(得分:1)

假设fields应该是列名。

CREATE OR REPLACE FUNCTION exa(ids text, length integer, fields text
                              ,OUT result text) AS
$BODY$
DECLARE
    _chars INT[] := string_to_array(ids, ',');
    i integer    := 0;
    _temp text   := '';
    _arr  text[];
BEGIN
    FOR i IN 1..length loop
        EXECUTE 'SELECT ' || fields || ' FROM user_index WHERE userid = chars[i]'
        INTO temp;
        _arr := _arr || temp;
    END LOOP;
    result := array_to_string(result, ',');

    RETURN;
END
$BODY$ language plpgsql;

真的 只是:

CREATE OR REPLACE FUNCTION exa(ids text, fields text, OUT result text) AS
$BODY$
BEGIN
   EXECUTE
   format($$SELECT string_agg(%I, ',')
            FROM   user_index
            JOIN   unnest(string_to_array($1, ',')::int[]) i(userid)
                                                      USING (userid)$$
         ,fields)
   USING ids
   INTO  result;
END
$BODY$ language plpgsql;

呼叫:

SELECT exa('10,11,12', 'kat')

请确保使用format()%I或其他一些理智的方法来避免SQL注入。试试搜索工具。这里有许多类似的答案 - 就像这个(有更多的解释和链接):
INSERT with dynamic table name in trigger function