Postgres: ОБЪЕДИНЯЙТЕ все столбцы

Я имею дело с таблицей, в которой слишком много столбцов для хорошего дизайна. (близко к 100). Я не могу изменить схему.

Мне нужно ОБЪЕДИНИТЬ каждый столбец, чтобы он был равен 0 на NULL. Есть ли способ сделать это без ввода всех 100 столбцов вручную? (Возможно, используя какой-то словарь данных или метаинформацию?)


person SRobertJames    schedule 08.01.2017    source источник


Ответы (1)


Вы можете создать функцию Postgres для достижения желаемого результата.

Пример таблицы и данных -

create table t(id serial, col1 int, col2 int, col3 int, col4 int, col5 int, col6 int, coln int); 
insert into t values ( 1, 1, 2, null,null,null,1),(1, null, null, null,2,null,6);

Следующий оператор select создаст динамический select для получения всех таблиц с coalesce().

SELECT format('select %s from t', string_agg(format('coalesce(%s,0)', column_name), ',')) q
FROM information_schema.columns
WHERE table_schema = 'public'
    AND table_name = 't'

Результат:

q                                                                                                                                                   
--------------------------------------------------------------------------------------------------------------------------------------------------- 
select coalesce(id,0),coalesce(col1,0),coalesce(col2,0),coalesce(col3,0),coalesce(col4,0),coalesce(col5,0),coalesce(col6,0),coalesce(coln,0) from t 

(1 row(s) affected)

Вы можете обернуть это в функцию

 create or replace function get_table_t ()
returns setof t as $$
declare qry text;
begin
    SELECT format('select %s from t', string_agg(format('coalesce(%s,0)', column_name), ','))
    into qry
    FROM information_schema.columns
    WHERE table_schema = 'public'
        AND table_name = 't'; 
    return query

    execute qry;
end;$$
LANGUAGE plpgsql VOLATILE

Использование: select * from get_table_t()

Выход:

id col1 col2 col3 col4 col5 col6 coln 
-- ---- ---- ---- ---- ---- ---- ---- 
1  1    2    0    0    0    1    0    
1  0    0    0    2    0    6    0    
person Vivek S.    schedule 09.01.2017