zoukankan      html  css  js  c++  java
  • 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)

     
  • 相关阅读:
    Microsoft SQL Server 2008 基本安装说明
    微软的招聘哲学——做微软人的五大核心素质
    大型网站性能优化的通用方法
    模型驱动的开发,回忆一年多前的一次开发
    远离客户陷阱小故事 转
    单例模式(Singleton)
    真的很高兴,就在今天“博客园团队”为我们开通了 “CSLA 团队”
    桥接模式(Bridge)与合成/聚合复用原则(CARP)
    2009年11月11日
    虚拟化的好处 随笔
  • 原文地址:https://www.cnblogs.com/winkey4986/p/6274729.html
Copyright © 2011-2022 走看看