如何使用循环创建1-10列?

时间:2017-10-27 13:30:30

标签: postgresql

这是一个示例,但我只想要一个包含1-10个值而没有其他文本列的列。

CREATE OR REPLACE FUNCTION somefun_recordset(param_numcount integer)
  RETURNS SETOF record AS
$$
DECLARE
    result text := '';
    searchsql text := '';
    var_match record;
BEGIN
    searchsql := 'SELECT n || '' down'' As countdown, n as integer 
                FROM generate_series(' || CAST(param_numcount As text) || ', 1, -1) As n ';


    FOR var_match IN EXECUTE(searchsql) LOOP
        RETURN NEXT var_match;
    END LOOP;
END;
$$
LANGUAGE 'plpgsql' IMMUTABLE;


SELECT r.n , r.countdown
FROM somefun_recordset(10) 
    As r(countdown text, n integer)
    ORDER BY r.n;

如何在postgres中创建循环?

1 个答案:

答案 0 :(得分:1)

从您当前的描述中,您似乎过于复杂了。

作为described in the Postgres manualgenerate_series函数可以生成一个从10到1的值列,如下所示:

SELECT generate_series(10, 1, -1) as n;

或者将其用作表别名而不是列别名:

SELECT * FROM generate_series(10, 1, -1) as n;

如果你想将它包装在只有一个参数的自定义函数中,它将如下所示:

CREATE FUNCTION countdown(param_numcount INT) RETURNS SETOF INT LANGUAGE SQL AS $$
    SELECT generate_series(param_numcount, 1, -1);
$$;

然后你将它运行为:

SELECT countdown(10) as n;