使用Pl / pgSQL将参数传递给循环中的查询

时间:2012-09-20 22:49:03

标签: postgresql plpgsql

我正在尝试创建一个参数化查询,该查询将使用plpgsql在循环中执行。

2个参数将是传递给查询的起始纬度/经度点。将从数组中检索纬度和经度点 - 因此它将像数组上的迭代一样,并且每次执行时将两个lat / lon值传递给查询。

我该怎么办?

我的查询和我认为的实现方式如下:( X,Z值是将传递的参数纬度/经度值,Y和T将通过执行我将处理的某个计算获得) 。为清楚起见,我的查询返回多行和多列结果(时间戳和计数),因为它计算并返回落入小时间隔(时间戳)的请求数

for each latitude-longitude pair X,Z in array

find Y and T from X and Z

WITH cal AS (
    SELECT generate_series('2011-02-02 00:00:00'::timestamp ,
                           '2012-04-01 05:00:00'::timestamp , 
                           '1 hour'::interval) AS stamp
),
qqq AS (
  SELECT date_trunc('hour', calltime) AS stamp, count(*) AS zcount
  FROM mytable
  WHERE calltime >= '2011-02-13 22:55:11' 
    AND calltime <= '2012-02-13 01:02:21'
    AND (calltime::time >= '22:55:11' 
    OR calltime::time <= '01:02:21')
    AND lat >= X 
    AND lat <= Y
    AND lon >= Z
    AND lon <= T
 GROUP BY date_trunc('hour', calltime)
)
SELECT cal.stamp, COALESCE (qqq.zcount, 0) AS zcount
FROM cal
LEFT JOIN qqq ON cal.stamp = qqq.stamp
WHERE cal.stamp >= '2011-02-13 22:00:00' 
  AND cal.stamp <= '2012-02-13 01:02:21' 
  AND (
    extract ('hour' from cal.stamp) >= extract ('hour' from '2011-02-13 22:00:00'::timestamp) or
    extract ('hour' from cal.stamp) <= extract ('hour' from '2012-02-13 01:02:21'::timestamp) 
  )
ORDER BY stamp ASC;

1 个答案:

答案 0 :(得分:2)

  • 将数组传递给函数,并将FOR r IN SELECT * FROM unnest(the_array) LOOP传递给数组中的元素,其中rrecord变量,位于DECLARE子句中功能;或

  • 循环传递给函数的refcursor。请参阅PL/PgSQL cursors

更好的是,避免使用LOOP并将SELECT unnest(thearray)集成到您的CTE中。 PL / PgSQL中的循环比SQL CTE中的循环要慢得多。

请参阅unnestLOOP