简体   繁体   English

将 Varchar 列中的所有数据转换为日期格式

[英]Converting all data in a Varchar column to a date format

I'm working on a table with a column, 'Expiry Date', as a varchar with all data formatted as DD/MM/YYYY.我正在处理一个带有“到期日期”列的表,它是一个 varchar,所有数据的格式都为 DD/MM/YYYY。

The creator of the table has used the wrong type for this expiry date column and now the client needs to filter and show all records before and after the current date as the time.表的创建者为此到期日期列使用了错误的类型,现在客户端需要过滤并显示当前日期之前和之后的所有记录作为时间。 This means the type needs to be changed to date or datetime type to be able to use the CURDATE() function.这意味着需要将类型更改为日期或日期时间类型才能使用 CURDATE() function。

However, the current format of the values does not satisfy and wont allow the type to change unless the format is changed to YYYY-MM-DD (or similar).但是,值的当前格式不满足并且不允许类型更改,除非格式更改为 YYYY-MM-DD(或类似格式)。

Is there any way to mass format the values in this column and this column alone as there are thousands of entries and formatting one by one would be extremely time consuming.是否有任何方法可以批量格式化此列和仅此列中的值,因为有数千个条目并且逐个格式化将非常耗时。

What you need is an update on that column, but before doing it I suggest you to check if the result is what you want.您需要的是对该列的更新,但在这样做之前,我建议您检查结果是否是您想要的。

select replace(expiry_date, '/', '-') new_expiry_date
  from table_name

If this returns the results you want you can run the following update:如果这返回您想要的结果,您可以运行以下更新:

update table_name
   set expiry_date = replace(expiry_date, '/', '-')

Of course you will need to replace expiry_date and table_name with the names of your column and table.当然,您需要将expiry_datetable_name替换为您的列和表的名称。

Let me assume that you are using MySQL.假设您使用的是 MySQL。

Perhaps the simplest method is to add a generated column that is a date:也许最简单的方法是添加一个生成的日期列:

alter table t add column expiry_date_date as
    (str_to_date(expiry_date, '%d/%m/%Y'));

You can also fix the data:您还可以修复数据:

update t
    set expiry_date = str_to_date(expiry_date, '%d/%m/%Y');

This will implicitly convert the result of str_to_date() to a date, which will be in the YYYY-MM-DD format.这会将str_to_date()的结果隐式转换为日期,该日期将采用 YYYY-MM-DD 格式。

More importantly, you can then do:更重要的是,您可以这样做:

alter table t modify column expiry_date date;

Here is a db<>fiddle. 是一个 db<>fiddle。

You can do similar operations in other databases, but the exact code is a bit different.您可以在其他数据库中执行类似的操作,但确切的代码有点不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM