Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

update vachar column to date in postgreSQL

Trying to update a column with varchar datatype e.g. '1950-08-14' to a date datatype using

UPDATE tablename SET columnname = to_date(columnname, 'YYYY-MM-DD');

or

ALTER TABLE tablename ALTER COLUMN columnname TYPE DATE USING to_date(columnname, 'YYYY-MM-DD');

but both return the error message

ERROR:  invalid value "columnname" for "YYYY"
DETAIL:  Value must be an integer.

Referencing http://www.postgresql.org/docs/9.4/static/functions-formatting.html

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The query:

ALTER TABLE tablename 
    ALTER COLUMN columnname TYPE DATE USING to_date(columnname, 'YYYY-MM-DD');

is correct.

The error message means that you have invalid value in column columnname (actualy the invalid value is 'columnname'). All the values in the column must have the format 'YYYY-MM-DD', e.g. '2015-01-01' (or be null).


Solution with a new column.

Create a function to convert varchar to date which returns null for invalid values:

create or replace function varchar_to_date_or_null(str varchar)
returns date language plpgsql as $$
begin
    return to_date(str, 'YYYY-MM-DD');
exception
    when invalid_datetime_format then return null;
end $$;

Add a new column and update it using the function:

alter table tablename add new_column date;

update tablename
set new_column = varchar_to_date_or_null(columnname);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...