【问题标题】:Postgres DB Column Type ConversionPostgres DB 列类型转换
【发布时间】:2018-05-14 03:22:34
【问题描述】:

试图将字符串列转换为日期。列当前包含值,例如“20170130”和“20161130”。

当我尝试时:

change_column :tickets, :string_date, :date

这给了我一个错误:

PG::DatatypeMismatch: ERROR:  column "string_date" cannot be cast automatically to type date. 
HINT:  Specify a USING expression to perform the conversion.

所以,我试试:

change_column :tickets, :string_date, 'date USING CAST(string_date AS date)'

仍然没有运气,出现以下错误:

PG::InvalidDatetimeFormat:错误:日期类型的输入语法无效

谁知道怎么回事??认为从字符串转换为日期会更容易......

提前致谢

【问题讨论】:

    标签: ruby-on-rails ruby database postgresql migration


    【解决方案1】:

    奇怪 - 我希望看到你未能投射日期的值,例如:

    t=# create table a2(string_date text);
    CREATE TABLE
    t=# insert into a2 values ('20170130'),('20161130');
    INSERT 0 2
    t=# insert into a2 select 'bad value';
    INSERT 0 1
    t=# alter table a2 alter COLUMN string_date type date using string_date::date;
    ERROR:  invalid input syntax for type date: "bad value"
    

    也许它是一个空字符串?..

    无论如何 - 找到不好的价值并修复它,然后尝试再次转换:

    t=# select string_date from a2 where string_date !~ '\d{8}';
     string_date
    -------------
     bad value
    (1 row)
    t=# begin;
    BEGIN
    t=# delete from a2 where string_date !~ '\d{8}';
    DELETE 1
    t=# alter table a2 alter COLUMN string_date type date using string_date::date;
    ALTER TABLE
    t=# end;
    COMMIT
    

    【讨论】:

    • 这对我帮助很大!谢谢!原来有一个糟糕的记录(呸,不敢相信我以前没有注意到它)。我删除了不良记录,然后繁荣,就这样!谢谢!
    猜你喜欢
    • 2012-11-20
    • 2016-07-19
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多