我只想在PostgreSQL中创建一个简单的循环

时间:2013-07-13 10:17:06

标签: sql postgresql loops for-loop

在PostGIS SQL编辑器中,我只想制作一个循环来使这个功能起作用

For Loopid = 0 to 1000, then execute the following statments:

UPDATE public.globaldtm 
SET "UTM" = loopid 
WHERE rid IN (SELECT rid FROM globaldtm WHERE ST_Intersects(rast,(select geom from utm where gid =loopid)));

enter image description here

如何在此SQL编辑器中编写简单代码以使循环工作。谢谢。

2 个答案:

答案 0 :(得分:4)

generate_series()的可选FROM子句中使用set-returning update statement函数:

UPDATE public.globaldtm 
SET UTM = loopid
FROM generate_series(0, 1000) as x(loopid) -- Added this line
WHERE rid IN (SELECT rid FROM globaldtm WHERE ST_Intersects(rast,(select geom from utm where gid =loopid)));

这是您的查询,添加以下行:

FROM generate_series(0, 1000) as x(loopid)

查看类似简化查询的live demo on SQLFiddle

答案 1 :(得分:2)

创建一个函数:

CREATE OR REPLACE FUNCTION updateValuesWithLoop()
RETURNS void
AS $$
BEGIN
  FOR Loopid  IN 0..1000 LOOP
    UPDATE public.globaldtm 
       SET "UTM" = loopid 
     WHERE rid IN (SELECT rid FROM globaldtm WHERE ST_Intersects(rast,(select geom from utm where gid =loopid)));
  END LOOP;
  RETURN;
END;
$$ LANGUAGE plpgsql;

执行功能:

select updateValuesWithLoop()