воскресенье, 27 марта 2016 г.

CREATE OR REPLACE VIEW

Команда CREATE OR REPLACE VIEW не всегда может пересоздать представление.
Используя вариант CREATE OR REPLACE в представление можно добавлять новые столбцы или изменять алгоритм расчета существующих.
 
postgres=# create view v (col1)
postgres-#    as select 1 as col1;
CREATE VIEW
postgres=# create or replace view v (col1, col2)
postgres-#    as select 11 as col1, 22 as col2;
CREATE VIEW
 
Но попытка переименовать столбец (поставим на первое место col0, вместо col1):
 
postgres=# create or replace view v (col0, col1, col2)
postgres-#    as select 0 as col0, 1 as col1, 2 as col2;
ERROR:  cannot change name of view column "col1" to "col0"

... или изменить тип данных приводят к ошибке:
 
postgres=# create or replace view v (col1, col2)
postgres-#    as select '11'::text as col1, 22 as col2;
ERROR:  cannot change data type of view column "col1" from integer to text 

В таких случаях нужно удалять и заново создавать представление:
 
postgres=# drop view v;
DROP VIEW
postgres=# create or replace view v (col0, col1, col2)
postgres-#    as select 0 as col0, 1 as col1, 2 as col2;
CREATE VIEW

Такая логика работы понятна и документирована:
"The new query must generate the same columns that were generated by the existing view query (that is, the same column names in the same order and with the same data types), but it may add additional columns to the end of the list. The calculations giving rise to the output columns may be completely different."
Но отличается от Oracle, где у CREATE OR REPLACE VIEW таких ограничений нет.

Комментариев нет: