2016-02-04 17 views
2

У меня есть функция следующим образом:имя таблицы в качестве переменной в 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 

Мне нужно изменить эту функцию, чтобы сделать еще один параметр, который говорит, если использовать 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 

Как определить, какую таблицу использовать?

ответ

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 
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 
+0

Создание временной таблицы не нужно –

Смежные вопросы