简体   繁体   English

sql 如何比较存储在 varchar 数据类型中的日期

[英]How sql compares date stored in varchar datatype

How a comparison between two dates are made if both are stored in varchar?如果两个日期都存储在 varchar 中,如何在两个日期之间进行比较?

I came across a table which is written years ago in which the date (DD-MM-YY) is stored in a varchar format我遇到了一个多年前写的表格,其中日期 (DD-MM-YY) 以 varchar 格式存储

updated_date varchar(255)

There's a script written for delete operation in following manner有一个为删除操作编写的脚本,如下所示

(Temp variable)- (温度变量)-

temp_date_tocompare varchar2(255) :=to_char(sysdate-7, 'YYYY-MM-DD')

delete from myTable
    where updated_date < temp_date_tocompare;

I executed this and it works fine.我执行了这个,它工作正常。

But curious to understand behind the scenes work, how this varchars are compared.但是很想了解幕后工作,如何比较这些 varchars。

Compare dates as dates .将日期作为日期进行比较。 Store date/times using proper date/time formats.使用正确的日期/时间格式存储日期/时间。 Do not store them as strings!不要将它们存储为字符串!

Your code will no doubt delete rows.您的代码无疑会删除行。 Whether it deletes the rows you want is another question.它是否删除您想要的行是另一个问题。 The logic you want seems to be:你想要的逻辑似乎是:

delete from myTable
    where to_date(updated_date, 'DD-MM-YY') < trunc(sysdate) - 7;

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

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