简体   繁体   English

在SQL SERVER中将VARCHAR转换为DATE

[英]Convert VARCHAR to DATE in SQL SERVER

I have VARCHAR column (MyValue) in my table. 我的表中有VARCHAR列(MyValue)。 It has date value in two different format. 它具有两种不同格式的日期值。

MyValue
----------
25-10-2016
2016-10-13

I would like to show them in DATE format. 我想以DATE格式显示它们。

I wrote query like below: 我写了如下查询:

SELECT CONVERT(date, MyValue, 105) FROM MyTable
SELECT CAST(MyValue as date) FROM MyTable

Both are giving me this error. 两者都给我这个错误。 Conversion failed when converting date and/or time from character string.

Is there anyway convert to DATE datatype format even the value stored in different formats like above? 无论如何,是否有转换为DATE数据类型格式的信息,甚至还有以上述不同格式存储的值?

Expecting your answers. 期待您的回答。 Thanks in advance. 提前致谢。

You can use TRY_CONVERT and COALESCE . 您可以使用TRY_CONVERTCOALESCE TRY_CONVERT returns NULL if the conversion fails, COALESCE returns the first NOT NULL value: 如果转换失败,则TRY_CONVERT返回NULL, COALESCE返回第一个NOT NULL值:

SELECT  COALESCE(TRY_CONVERT(DATETIME, x, 105), TRY_CONVERT(DATETIME, x, 120))
FROM    (VALUES('25-10-2016'), ('2016-10-13')) a(x)

I assumed the value 2016-10-13 is in format yyyy-MM-dd . 我假设值2016-10-13的格式为yyyy-MM-dd

You mention in a comment you may have other formats as well. 您在评论中提到您可能还有其他格式。 In that case it gets very tricky. 在这种情况下,它变得非常棘手。 If you get a value 01-12-2017 and you have no idea about the format, there is no way to tell whether this is a date in januari or in december. 如果您获得的值是01-12-2017并且不知道格式,则无法分辨这是1月还是12月。

Does this help? 这有帮助吗?

declare @varchardates table
(
vcdate varchar(20)
)

INSERT INTO @varchardates VALUES
('25-10-2016'),
('2016-10-13')

SELECT CONVERT(date,vcdate, case when SUBSTRING(vcdate, 3, 1) = '-' 
THEN 105 ELSE 126 END) as mydate 
FROM @varchardates  

Depending on how many different formats you have in your data, you may need to extend the case statement! 根据数据中有多少种不同的格式,您可能需要扩展case语句!

See here for list of the different format numbers 请参阅此处以获取不同格式编号的列表

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

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