表名作为postgresql中的变量

时间:2016-02-04 08:26:26

标签: sql postgresql

我的功能如下:

table_a

我需要更改此函数以使用另一个参数来判断是使用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

{{1}}

如何确定使用哪个表?

2 个答案:

答案 0 :(得分:3)

使用dynamic 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

答案 1 :(得分:2)

使用临时表根据条件从表中获取数据。

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


    drop  table if exists temp_data;
    if whichtouse=1
    then 
        create temporary table temp_data as
        Select id  from table_a    where quantity=1;
    else
        create temporary table temp_data as
        Select id  from table_b    where quantity=1;
    end if;

    for rec in Select id  from temp_data 
    loop
        -- do something here
    end loop;

end;
$BODY$
LANGUAGE plpgsql VOLATILE
相关问题