簡體   English   中英

我們如何在 postgresql 中聲明 cursor 中的變量

[英]how can we declare a variable in cursor in postgresql

我想將 fetch 的結果存儲到一個變量中,我們如何在 postgresql 中做到這一點?

我還嘗試創建一個 function 它不起作用

代碼:

begin work;

DECLARE 

    cur_films CURSOR
       FOR select CURRENT_DATE + i date_
       FROM  generate_series(date '2019-11-11'- CURRENT_DATE,  date '2019-11-15' - CURRENT_DATE ) i;
       fetch forward 2 from cur_films;

close cur_films;

commit work; 

如果要將查詢生成的所有值傳遞給 function 或過程,可以將所有內容聚合到一個數組中,然后將該數組傳遞給 function:

DECLARE 
  l_dates date[];
begin
  select array_agg(g.dt::date)
    into l_dates
  from generate_series(date '2019-11-11',  date '2019-11-15', interval '1 day') as g(dt);

  perform your_function(l_dates);
end;

但是你不需要 PL/pgSQL。 這也可以在普通 SQL 中完成:

with input as (      
  select array_agg(g.dt::date) as dates
  from generate_series(date '2019-11-11',  date '2019-11-15', interval '1 day') as g(dt)
)
select *
from your_function((select dates from input));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM