PostgreSQL loops outside functions. Is that possible?

[亡魂溺海] 提交于 2019-12-06 01:45:55

问题


I'm making comparative about PostgreSQL vs. SQLServer for migrating purposes. Now I'm evaluating T-SQL vs. PL/pgSQL, the thing is that in T-SQL you can use loops or declare variables, for example:

declare @counter int
set @counter = 0
while @counter < 10
begin
   set @counter = @counter + 1
   print 'The counter is ' + cast(@counter as char)
end

There is no need to put it inside a function or procedure. Can I do that in PostgreSQL?

Searching on the web I found a negative answer doing it in MySQL but I didn't find such answer for Postgres.


回答1:


You cannot DECLARE (global) variables (well, there are ways around this) nor loop with plain SQL - with the exception of recursive CTEs as provided by @bma.

However, there is the DO statement for such ad-hoc procedural code. Introduced with Postgres 9.0. It works like a one-time function, but does not return anything. You can RAISE notices et al, so your example would just work fine:

DO
$do$
DECLARE
   _counter int := 0;
BEGIN
   WHILE _counter < 10
   LOOP
      _counter := _counter + 1;
      RAISE NOTICE 'The counter is %', _counter;  -- coerced to text automatically
   END LOOP;
END
$do$

If not specified otherwise, the language in the body is plpgsql. You can use any registered procedural language though, if you declare it (like: LANGUAGE plpython).

Postgres also offers generate_series() to generate sets ad-hoc, which may obviate the need for looping in many cases. Try a search here on SO for examples.

Also, you can use the WHERE clause in a data-modifying CTE in plain SQL to fork cases and emulate IF .. THEN .. ELSE .. END ...




回答2:


You can recursively query result sets using WITH RECURSIVE, assuming you are on Postgresql 8.4+. Docs: http://www.postgresql.org/docs/current/static/queries-with.html

This would allow you to loop your set and process the data in various ways.



来源:https://stackoverflow.com/questions/18340929/postgresql-loops-outside-functions-is-that-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!