2013-02-08 34 views
9

Sau đây là một đoạn của bảng được gọi là "vùng chứa".Thay đổi một cột từ chuỗi thành chuỗi trong postgresql

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

Làm thế nào tôi có thể thay đổi cột products-"character varying[]" và bổ tương ứng để default '{}'::character varying[]? Về cơ bản, tôi muốn chuyển đổi một chuỗi thành một mảng chuỗi. Lưu ý cột sản phẩm không có giới hạn về số ký tự.

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

ném các lỗi sau

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

Trả lời

11

Không có diễn viên tiềm ẩn varchar-varchar[] trong Postgres. Bạn phải chỉ ra cách thực hiện chuyển đổi các loại. Bạn nên làm điều đó trong mệnh đề USING expression (xem ALTER TABLE trong tài liệu). Trong trường hợp đó bạn phải thả và tạo giá trị mặc định của cột, vì nó được giải thích trong tài liệu hướng dẫn:

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 '{}'; 

Ba hoạt động có thể được thực hiện trong một tuyên bố:

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

Cảm ơn. Tuy nhiên, nếu bạn gặp lỗi này, bạn có thể bỏ qua mặc định cho cột "sản phẩm" để nhập văn bản [] – papdel

+0

tạo hoặc thay thế hàm string_to_string_array (giá trị ký tự khác nhau) trả về ký tự [] ngôn ngữ sql là $$ chọn mảng [$ 1] $$; và sau đó thay đổi bảng "vùng chứa" thay đổi "sản phẩm" loại ký tự thay đổi [] bằng cách sử dụng string_to_string_array (sản phẩm); cũng đã ném cùng một lỗi. – papdel

+0

Làm cách nào để thay đổi giá trị mặc định hiện tại? – papdel

Các vấn đề liên quan