简体   繁体   English

SQL varchar 列到具有 2 个标准的日期列

[英]SQL varchar column to date column with 2 standards

I have a table with a column varchar(2048) and inside I have data in date format.我有一个带有 varchar(2048) 列的表,里面有日期格式的数据。

But my data is in the format "20/12/2021" (British standard) and also "12/20/2021" (US standard).但我的数据格式为“20/12/2021”(英国标准)和“12/20/2021”(美国标准)。

Can I convert the varchar column in a date column with both standards?我可以使用两种标准转换日期列中的 varchar 列吗?

This is a data/business problem and so will need further decisions by someone who knows the data/business.这是一个数据/业务问题,因此需要了解数据/业务的人做出进一步的决定。

As you do not know what format this data is in, you can work out some, but not all - for example:由于您不知道此数据的格式,您可以计算出一些,但不是全部 - 例如:

SELECT 
    *,
    SUBSTRING(D.Date, 0, CHARINDEX('/', D.Date)),
    SUBSTRING(D.Date, CHARINDEX('/', D.Date) + 1, CHARINDEX('/', D.Date, CHARINDEX('/', D.Date)) - 1),

    CASE 
        WHEN SUBSTRING(D.Date, 0, CHARINDEX('/', D.Date)) > 12 THEN 'UK Date'
        WHEN SUBSTRING(D.Date, CHARINDEX('/', D.Date) + 1, CHARINDEX('/', D.Date, CHARINDEX('/', D.Date)) - 1) > 12 THEN 'US Date'
        ELSE 'Indeterminate Date'
    END
FROM 
    ( VALUES 
        ('30/05/2020'),
        ('10/25/2020'),
        ('08/06/2020')
    ) AS D (Date);

You would need to prepare a list of the indeterminate dates and use other information from your data to work out which is which.您需要准备一份不确定日期的列表,并使用您数据中的其他信息来确定哪个是哪个。 For example, if these are order dates and there are also shipping dates you could work out because you expect the dates to be close:例如,如果这些是订单日期,并且还有发货日期,您可以计算出,因为您希望日期接近:

Order Date: 02/06/2020 Shipping Date: 02/09/2020订购日期: 02/06/2020发货日期: 02/09/2020

Therefore (unless your company takes 3 months to despatch), this is an American date.因此(除非贵公司需要 3 个月才能发货),这是一个美国日期。

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

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