2013-02-08 21 views
9

Poniżej znajduje się fragment tabeli o nazwie "containers".Zmiana kolumny z łańcucha znaków na ciąg znaków w postgresql

 Column  |   Type    |   Modifiers    
--------------------+-----------------------------+--------------------------------- 
id     | uuid      | not null 
name    | character varying(255)  | 
products   | character varying   | default '{}'::character varying 

Jak można zmieniać kolumnę products do "character varying[]" i odpowiednie modyfikatory default '{}'::character varying[]? Zasadniczo chcę przekonwertować ciąg na tablicę ciągów. Uwaga: kolumna produktów nie ma limitu liczby znaków.

alter table "containers" alter "products" type character varying[]; 

wyrzuca następujący błąd

ERROR: column "products" cannot be cast to type character varying[]

Odpowiedz

11

Nie ma niejawny oddanych od varchar do varchar[] w PostgreSQL. Należy wskazać, jak wykonać konwersję typów. Powinieneś to zrobić w klauzuli USING expression (w dokumentacji patrz ALTER TABLE). W takim przypadku trzeba usunąć i odtworzyć domyślną wartość kolumny, jak to jest opisane w dokumentacji:

The USING option of SET DATA TYPE can actually specify any expression involving the old values of the row; that is, it can refer to other columns as well as the one being converted. This allows very general conversions to be done with the SET DATA TYPE syntax. Because of this flexibility, the USING expression is not applied to the column's default value (if any); the result might not be a constant expression as required for a default. This means that when there is no implicit or assignment cast from old to new type, SET DATA TYPE might fail to convert the default even though a USING clause is supplied. In such cases, drop the default with DROP DEFAULT, perform the ALTER TYPE, and then use SET DEFAULT to add a suitable new default.

alter table containers alter products drop default; 
alter table containers alter products type text[] using array[products]; 
alter table containers alter products set default '{}'; 

The trzy operacje mogą być wykonane w jednym stwierdzeniem:

alter table containers 
    alter products drop default, 
    alter products type text[] using array[products], 
    alter products set default '{}'; 
+0

Dzięki. Jak uzyskać ten błąd rzucania - ERROR: domyślnie dla kolumny "produkty" nie można rzutować na tekst tekstowy [] – papdel

+0

twórz lub zamień funkcję string_to_string_array (zmieniając znak wartości) zwraca znak zmieniając [] język sql jako $$ wybierz tablicę [$ 1] $$; a następnie zmieniają tabelę "pojemniki" zmieniają "rodzaj produktu" znak zmieniający się [] za pomocą string_to_string_array (produkty); rzucił ten sam błąd, jak również. – papdel

+0

Jak również zmienić istniejącą wartość domyślną? – papdel

Powiązane problemy