我们如何在Postgresql中的游标中声明变量

时间:2019-11-11 10:54:15

标签: postgresql plpgsql

我想将fetch的结果存储到变量中,如何在postgresql中做到这一点?

我还尝试通过创建不起作用的功能

代码:

# Now, we dynamically create an empty array with the dtypes from our structured array and our new column:
dtypes = []
for array in [arr, new_col]:
    for name in array.dtype.names:
        dtype = (name, array[name].dtype)
        dtypes.append(dtype)
new_arr = np.empty(len(new_col), dtype=dtypes)

# Finally, put your data in the empty array:
for array in [arr, new_col]:
    for name in array.dtype.names:
        new_arr[name] = array[name]

1 个答案:

答案 0 :(得分:0)

如果要将查询生成的所有值传递给函数或过程,可以将所有内容聚合到一个数组中,然后将该数组传递给该函数:

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));