2013-02-08 43 views
9

में स्ट्रिंग से स्ट्रिंग सरणी से कॉलम बदलना निम्नलिखित "कंटेनर" नामक तालिका का एक स्निपेट है।पोस्टग्रेस्क्ल

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

मैं "character varying[]" को products स्तंभ और default '{}'::character varying[] को इसी संशोधक कैसे बदल सकते हैं? अनिवार्य रूप से, मैं एक स्ट्रिंग को स्ट्रिंग सरणी में कनवर्ट करना चाहता हूं। ध्यान दें कि उत्पाद कॉलम की संख्या वर्णों की कोई सीमा नहीं है।

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

निम्न त्रुटि

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

उत्तर

11

फेंकता कोई अंतर्निहित Postgres में varchar[] करने के लिए varchar से डाली है। आपको इंगित करना होगा कि प्रकारों का रूपांतरण कैसे करें। आपको इसे USING expression खंड में करना चाहिए (दस्तावेज में ALTER TABLE देखें)। उस मामले तुम, ड्रॉप और स्तंभ का डिफ़ॉल्ट मान से बनाना के रूप में यह दस्तावेज में समझाया गया है में:

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

तीन आपरेशनों एक बयान में किया जा सकता है:

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

धन्यवाद। हालांकि इस कास्ट त्रुटि को प्राप्त करना - त्रुटि: कॉलम "उत्पादों" के लिए डिफ़ॉल्ट को टेक्स्ट टाइप करने के लिए नहीं बदला जा सकता है [] – papdel

+0

फ़ंक्शन स्ट्रिंग_to_string_array (मूल्य वर्ण भिन्न) को बना या प्रतिस्थापित करें चरित्र अलग-अलग [] भाषा एसक्यूएल $$ सरणी का चयन करें [$ 1] $$; और फिर स्ट्रिंग_to_string_array (उत्पादों) का उपयोग कर तालिका "कंटेनर" में परिवर्तन "उत्पादों" प्रकार भिन्नता [] बदलते हैं; ने भी वही त्रुटि फेंक दी। – papdel

+0

मैं मौजूदा डिफ़ॉल्ट मान को कैसे बदलूं? – papdel