对于表中的行,将行保存到临时表中以在plpgsql中的select查询中使用其数据

时间:2018-10-03 15:58:50

标签: for-loop iteration row plpgsql

我想做这样的事情,但不确定用于在表上迭代for循环的数据类型记录的行变量是否可以插入同一个for循环本身中的临时表

CREATE OR REPLACE FUNCTION LoopThroughTable() 
RETURNS VOID 
AS
$$
DECLARE 
t_row record;
BEGIN
   FOR t_row in SELECT * FROM the_table
      LOOP
      create temp table tmp as (select * from t_row); --- is this possible??
      --- use the data of tmp table in some select query
      drop table tmp; -- is this possible??
      END LOOP;
END;
$$ 
LANGUAGE plpgsql;

如果可能,有人可以帮助我提供正确的语法吗?

1 个答案:

答案 0 :(得分:0)

想通了!

只要有人偶然发现了这篇文章,访问 t_row记录这类数据的有效方法就是:

CREATE OR REPLACE FUNCTION LoopThroughTable() 
RETURNS VOID 
AS
$$
DECLARE 
   t_row record;
BEGIN
   FOR t_row in SELECT * FROM table_1
       LOOP
          SELECT * FROM table_2 when A= t_row.B 
          -- where A is a column in table_2 whose value should be equal to column B in t_row (which single row from table_1) 
       END LOOP;
END;
$$ 
LANGUAGE plpgsql;