PostgreSQL ALTER TABLE中改變數據類型時USING的用法<轉>


在修改表字段類型的時候使用Using來進行顯示的轉換類型。

原文說明:

SET DATA TYPE 
  This form changes the type of a column of a table. Indexes and simple table constraints involving the column willbe automatically converted to use the new column type by reparsing the originally supplied expression. The optional COLLATE clause specifies a collation for the new column; if omitted, the collation is the default for the new column type. The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

  大致意思是:轉換類型的時候有隱含類型轉換的時候,會自動轉換,如果沒有,那么就必須使用using指定一下轉換規則。

1. 建表

create table 101(id integer);

2. 插入數據

insert into tb10 select generate_series(1,5);

3. 把id的int變為varchar

postgres=# alter table tb101 alter id type varchar; ALTER TABLE

 

因為int轉varchar有隱式的轉換,故可以自動轉換過去。

postgres=# \d tb101
 Table "public.tb101"  Column | Type | Modifiers --------+-------------------+-----------  id | character varying |

 

 

4. 把id的varchar變為int

postgres=# alter table tb101 alter id type int; ERROR: column "id" cannot be cast automatically to type integer HINT: Specify a USING expression to perform the conversion.

 

在沒有隱式的轉換下,就需要指定Using來顯示的轉換。

5. 使用Using進行類型轉換

postgres=# alter table tb101 alter id type int using id::int; ALTER TABLE postgres=# \d tb101 Table "public.tb101" Column | Type | Modifiers --------+---------+----------- id | integer | 

id::int 也可以使用cast(id as int)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM