对于Postgresql 9.1中具有动态表名的循环?

时间:2014-01-07 07:08:54

标签: postgresql dynamic-sql

我有一个plpgslq函数可以进行一些数据处理,并希望编写一个for循环,但是我的表名在设计时是未知的。有没有可能的方法来实现这一目标?以下是我想要实现的示例代码片段:

-- Function: check_data()

-- DROP FUNCTION check_data();

CREATE OR REPLACE FUNCTION check_data()
  RETURNS character varying AS
$BODY$declare
 dyn_rec record;
 tbl_name record;
begin
  -- sample dynamic tables
  tbl_name := 'cars';
  tbl_name := 'trucks';
  tbl_name := 'bicycles';

  for dyn_rec in select * from format($$s%$$,tbl_name) loop
    raise notice 'item is %',dyn_rec.item_no;
  end loop;

  return 'Processing Ok';

end;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION check_data()
  OWNER TO postgres;

1 个答案:

答案 0 :(得分:9)

您不能在plpgsql嵌入式SQL中将变量用作表或列标识符。解决方案是动态SQL - EXECUTE或FOR IN EXECUTE语句:

DO $$
DECLARE
  tables text[] = ARRAY['table1','table2'];
  table_name text;
  rec record;
BEGIN
  FOREACH table_name IN ARRAY tables
  LOOP
    FOR r IN EXECUTE format('SELECT * FROM %I', table_name)
    LOOP
      RAISE NOTICE '%', rec;
    END LOOP; 
  END LOOP;
END; $$