错误:查询没有结果数据的目的地:PostgreSQL

时间:2019-04-06 05:50:47

标签: postgresql function loops insert

我正在使用Postgresql11,并且当我用

添加LOOP语句时,一次运行中运行良好的函数失败
  

“错误:查询没有结果数据的目的地提示:如果要   放弃SELECT的结果,请改用PERFORM。“

该函数以VOID作为返回值,从源表中选择数据到临时表中,计算一些数据并将结果插入目标表中。然后删除临时表,函数结束。我想按定义的间隔重复此过程,并包含了LOOP语句。使用LOOP时,它不会插入到目标表中,并且实际上根本不会循环。


    create function transfer_cs_regular_loop(trading_pair character varying) returns void
        language plpgsql
    as
    $$
    DECLARE
        first_open decimal;
        first_price decimal;
        last_close decimal;
        last_price decimal;
        highest_price decimal;
        lowest_price decimal;
        trade_volume decimal;
        n_trades int;
        start_time bigint;
        last_entry bigint;
        counter int := 0;
        time_frame int := 10;

    BEGIN
        WHILE counter < 100 LOOP
            SELECT  max(token_trades.trade_time) INTO last_entry FROM token_trades WHERE token_trades.trade_symbol = trading_pair;
            RAISE NOTICE 'Latest Entry: %', last_entry;
            start_time = last_entry - (60 * 1000);
            RAISE NOTICE 'Start Time: %', start_time;
            CREATE TEMP TABLE temp_table AS
                SELECT * FROM token_trades where trade_symbol = trading_pair and trade_time > start_time;
            SELECT temp_table.trade_time,temp_table.trade_price INTO first_open, first_price FROM temp_table ORDER BY temp_table.trade_time ASC FETCH FIRST 1 ROW ONLY;
            SELECT temp_table.trade_time,temp_table.trade_price INTO last_close, last_price FROM temp_table ORDER BY temp_table.trade_time DESC FETCH FIRST 1 ROW ONLY;
            SELECT max(temp_table.trade_price) INTO highest_price FROM temp_table;
            SELECT min(temp_table.trade_price) INTO lowest_price FROM temp_table;
            SELECT INTO trade_volume sum(temp_table.trade_quantity) FROM temp_table;
            SELECT INTO n_trades count(*) FROM temp_table;
            INSERT INTO candlestick_data_5min_test(open, high, low, close, open_time, close_time, volume, number_trades, trading_pair) VALUES (first_price, highest_price, lowest_price, last_price, first_open, last_close, trade_volume, n_trades, trading_pair);
            DROP TABLE temp_table;
            counter := counter + 1;
            SELECT pg_sleep(time_frame);
            RAISE NOTICE '**************************Counter: %', counter;
        END LOOP;

    END;
    $$;

1 个答案:

答案 0 :(得分:0)

错误涉及函数中的最后SELECT条语句。如果有一个SELECT没有INTO,它将始终返回结果。如果没有LOOP,则此结果将用作该函数的返回值(即使它为空)。

在添加LOOP时,循环内没有SELECT的{​​{1}}就不会存在,因为将需要一个返回值,现在将有很多。在这种情况下,您需要使用INTO,它与PERFORM完全一样,但是会丢弃结果。

因此将最后一个SELECT更改为SELECT,错误将消失:

PERFORM
相关问题