将字符字段更改为日期 [英] Alter character field to date
本文介绍了将字符字段更改为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个旧的postgres数据库,日期列转换为字符(50)
字段(不要问)。我想更改表和列以包含实际日期。因为它工作了:
I've a legacy postgres db that has date columns cast as character(50)
fields (don't ask). I'd like to alter the table and columns to contain actual dates. Because this worked:
select distinct to_date(date_begin, 'YYYY DD MM') from dates;
我天真地认为这可能工作:
I naively thought this might work:
alter table dates alter column date_begin type character
using to_date(date_begin, 'YYYY DD MM');
但它不是。
推荐答案
这个只是工作我们在这里是一个简单的思考/打字。
阅读更多在关于ALTER TABLE 的手册。
演示:
This just works as intended by the OP. What we have here is a simple thinko/typo.
Read more in the manual about ALTER TABLE.
Demo:
-- DROP SCHEMA x CASCADE;
CREATE SCHEMA x;
CREATE TABLE x.tbl(date_begin character(50));
INSERT INTO x.tbl VALUES ('2011-11-11 11:11'), (NULL), (''), ('1977');
-- NULL and empty string work too
-- even just YYYY works: '1977' .. is converted to '1977-01-01' automatically
-- empty string produce a possibly surprising result: '0001-01-01 BC'
ALTER TABLE x.tbl ALTER COLUMN date_begin TYPE date USING to_date(date_begin, 'YYYY DD MM');
SELECT * FROM x.tbl;
提示:您写入类型字符
类型日期
。
这篇关于将字符字段更改为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文