【问题标题】:Run stored procedures in a loop based on a parameter根据参数循环运行存储过程
【发布时间】:2019-11-13 18:52:48
【问题描述】:

我有一个函数test_function,我将_snapdt 作为参数传递。我想在一个循环中单独运行这个函数几个日期(_snapdt)。

有人可以帮我解决这个问题吗?

例如,我想在 "2018-01-30" 、 2018-02-30" 等多个日期运行此函数..

目前我是这样手动运行的:

select * from test_function('2018-01-30') ;
select * from test_function('2018-02-30') ;

这里是函数

CREATE OR REPLACE FUNCTION test_function(_snapdt date) 
RETURNS integer
AS 
$BODY$
declare rows integer;
BEGIN

DROP TABLE IF EXISTS temp_table;
create table temp_table AS
select col1,col2 
    from table1
    where id=01000 and
    snapshot_date=_snapdt
group by col1,col2
distributed randomly;


INSERT INTO standard_table
(   snap_date,
    col1,
    col2
)
SELECT 
_snapdt as snap_date,
a.col1,
a.col2,
FROM temp_table a;

GET DIAGNOSTICS rows=ROW_COUNT;
DROP TABLE IF EXISTS temp_table;
return rows;
END;
$BODY$
LANGUAGE plpgsql; 

【问题讨论】:

    标签: sql postgresql stored-procedures


    【解决方案1】:

    使用generate_series()

    select test_function(t.dt::date)
    from generate_series(date '2018-01-30', date '2018-02-28') as t(dt);
    

    如果你想每个月调用一次函数,改变间隔:

    select test_function(t.dt::date)
    from generate_series(date '2018-01-01', date '2019-12-01', interval '1 month') as t(dt);
    

    【讨论】:

    • 我有从 2018 到 2019 的每月快照日期。我是否需要在生成系列函数中明确写入所有这些月度日期?
    • @user8545255:您可以更改生成日期的间隔。查看我的编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    相关资源
    最近更新 更多