LOOP循环

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

postgres=# CREATE OR REPLACE FUNCTION f27() RETURNS VOID AS
postgres-# $$    
postgres$# DECLARE
postgres$#      v_id INTEGER := 1;
postgres$# BEGIN           
postgres$#     LOOP       
postgres$#         RAISE NOTICE '%',v_id;
postgres$#         EXIT WHEN random()>0.8;
postgres$#         v_id := v_id + 1;
postgres$#     END LOOP ;
postgres$# END;
postgres$# $$
postgres-# LANGUAGE plpgsql;
CREATE FUNCTION
postgres=# SELECT f27();
NOTICE:  1
NOTICE:  2
 f27 
----- 
(1 row)
#使用EXIT退出循环
postgres=# CREATE OR REPLACE FUNCTION f27() RETURNS VOID AS
postgres-# $$    
postgres$# DECLARE
postgres$#     v_id INTEGER := 1;
postgres$#     v_random float8 ;
postgres$# BEGIN           
postgres$#     LOOP       
postgres$#        RAISE NOTICE '%',v_id;
postgres$#        v_id := v_id + 1;
postgres$#        v_random := random();
postgres$#        IF v_random > 0.8 THEN
postgres$#            RETURN;
postgres$#        END IF;
postgres$#     END LOOP ;
postgres$# END;
postgres$# $$
postgres-# LANGUAGE plpgsql;
CREATE FUNCTION
postgres=# SELECT f27();
NOTICE:  1
NOTICE:  2
NOTICE:  3
NOTICE:  4
NOTICE:  5
 f27 
-----
(1 row)
postgres=# 
#使用RETURN退出循环返回