postgresql 中的表名作为变量

jav*_*ava 6 sql postgresql

我有一个函数如下:

CREATE OR REPLACE FUNCTION func(a integer)
  RETURNS integer AS
$BODY$
begin

     for row in
                     Select id  from table_a    where quantity=1
    loop
        do something
    end loop

end;
$BODY$
  LANGUAGE plpgsql VOLATILE
Run Code Online (Sandbox Code Playgroud)

我需要更改此函数以采用另一个参数来告诉是否使用table_aor table_b

whichtouse=1我需要使用table_a.

whichtouse=2我需要使用table_b.

CREATE OR REPLACE FUNCTION func(a integer,whichtouse integer)
  RETURNS integer AS
$BODY$
begin

     for row in
                     Select id  from ??? where quantity=1
    loop
        do something
    end loop

end;
$BODY$
  LANGUAGE plpgsql VOLATILE
Run Code Online (Sandbox Code Playgroud)

如何确定使用哪个表?

小智 6

使用动态 SQL

CREATE OR REPLACE FUNCTION func(a integer, whichtouse integer)
  RETURNS integer AS
$BODY$
declare
  l_sql text;
  l_rec record;
begin
  if whichtouse = 1 then
    l_sql := format('select id from %I where qantity=1', 'table_a');
  else 
    l_sql := format('select id from %I where qantity=1', 'table_b');
  end if;

   for l_rec in execute l_sql
   loop
      -- do something
   end loop;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
Run Code Online (Sandbox Code Playgroud)