由于手误,利用PowerDesigner创建表字段的时候,有张表的时间字段类型选择成了timez(timestamp with time zone),本想直接从Navicat修改字段类型为timestamp(timestamp without time zone),没成想报了如下错误:
ERROR: column "create_time" cannot be cast automatically to type timestamp without time zone
HINT: You might need to specify "USING create_time::timestamp without time zone".
Navicat的sql预览提示的sql如下:
ALTER TABLE "public"."students" ALTER COLUMN "create_time" TYPE timestamp (6);
百度提供的大多数方法为在此提示方法后添加一句 using create_time::timestamp (6),整体sql如下:
ALTER TABLE "public"."students" ALTER COLUMN "create_time" TYPE timestamp (6) using create_time::timestamp (6);
实际试验,对于timez/timestamp时间戳类型的处理使用using直接修改字段的方法是没有作用的,其他字段类型的修改倒是可以用using的方法去操作,方法如下:
alter table "表名" alter column "字段名" type 字段类型 using "字段名"::字段类型;
--例如,将年龄字段从varchar转成int4:
alter table "students" alter column "age" type INTEGER using "age"::INTEGER
言归正传,pgsql这个时间类型间的表字段转换问题,后从stackoverflow上看到了一个解决方法,照抄原文执行也会报错(有可能是版本不一样的原因),后将其微调了一下,最终成功修改了字段类型。
修改后的sql如下:
--1、 创建一个类型为TIMESTAMP的临时字段
ALTER TABLE students ADD COLUMN tmp_column TIMESTAMP without time zone NULL;
--2、 使用using修改字段类型,用临时字段的类型修改原始字段的类型
ALTER TABLE students ALTER COLUMN create_time TYPE TIMESTAMP without time zone USING tmp_column;
--3、 最后删除临时字段
ALTER TABLE students DROP COLUMN tmp_column;
注意:本人所使用数据库为PostgreSQL
本文适用于从timez(timestamp with time zone)转换成timestamp(timestamp without time zone),当然也适用于从timestamp转换成timez