FOR循环

最近更新时间: 2024-06-12 15:06:00

postgres=# CREATE OR REPLACE FUNCTION f27() RETURNS VOID AS
postgres-# $$    
postgres$# BEGIN           
postgres$#     FOR i IN 1..3 LOOP
postgres$#         RAISE NOTICE 'i = %',i;
postgres$#     END LOOP;
postgres$# END;
postgres$# $$
postgres-# LANGUAGE plpgsql;
CREATE FUNCTION
postgres=# SELECT f27();
NOTICE:  i = 1
NOTICE:  i = 2
NOTICE:  i = 3
 f27 
----- 
(1 row)
postgres=# CREATE OR REPLACE FUNCTION f27() RETURNS VOID AS
postgres-# $$    
postgres$# BEGIN           
postgres$#     FOR i IN REVERSE 3..1 LOOP
postgres$#         RAISE NOTICE 'i = %',i;
postgres$#     END LOOP;
postgres$# END;
postgres$# $$
postgres-# LANGUAGE plpgsql;
CREATE FUNCTION
postgres=# SELECT f27();
NOTICE:  i = 3
NOTICE:  i = 2
NOTICE:  i = 1
 f27 
----- 
(1 row)
#使用REVERSE递减
postgres=# CREATE OR REPLACE FUNCTION f27() RETURNS VOID AS
postgres-# $$    
postgres$# BEGIN           
postgres$#     FOR i IN 1..8 BY 2 LOOP
postgres$#         RAISE NOTICE 'i = %',i;
postgres$#     END LOOP;
postgres$# END;
postgres$# $$
postgres-# LANGUAGE plpgsql;
CREATE FUNCTION
postgres=# SELECT f27(); 
NOTICE:  i = 1
NOTICE:  i = 3
NOTICE:  i = 5
NOTICE:  i = 7
 f27 
----- 
(1 row)
#使用BY设置步长