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)

     
  • 相关阅读:
    如何让某一个窗口位于所有的窗口最上面
    CString ,BSTR ,LPCTSTR之间关系和区别
    PPT演讲放映技巧__备注的妙用
    链接集合
    男人靠什么吸引女人
    配置IISweb容器之程序下载
    用windows2003免费搭建外网流媒体服务器
    人类记忆规律及法则
    MFC基础知识总结
    VC 定位窗体常用方法
  • 原文地址:https://www.cnblogs.com/winkey4986/p/6274729.html
Copyright © 2011-2022 走看看