2017-01-08 2 views
1

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

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

ответ

0

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