[英]How to convert string in 'DD/MM/YYYY' or 'YYYY-MM-DD' into date in SQL Server?
I've got a string here which needs to be converted into date but the problem is that it could either be in 'DD/MM/YYYY' or 'YYYY-MM-DD' format. 我在这里有一个字符串,需要将其转换为日期,但问题是它可能采用'DD / MM / YYYY'或'YYYY-MM-DD'格式。
I've already tried convert which only works for one of the two formats but not both: 我已经尝试过convert,它仅适用于两种格式之一,但不能同时适用于两种格式:
declare @string nvarchar(255) = '2019-05-21'
declare @table table (date date)
insert into @table
select convert(date, @string, 111) as date
select * from @table
declare @string nvarchar(255) = '21/05/2019'
declare @table table (date date)
insert into @table
select convert(date, @string, 103) as date
select * from @table
Both of the above solutions result in an error is I use the other format. 以上两种解决方案均导致错误,原因是我使用了其他格式。
Is there a way to get a string converted to date regardless of what format it is in? 有什么方法可以将字符串转换为日期,而不管其采用哪种格式?
Use try_convert()
: 使用
try_convert()
:
insert into @table
select coalesce(try_convert(date, @string, 111),
try_convert(date, @string, 103)
) as date
try_convert()
returns NULL
if the conversion fails. 如果转换失败,
try_convert()
返回NULL
。 In that case, the conversion will move on to the next pattern. 在这种情况下,转换将继续进行下一个模式。 With
coalesce()
, you can have as many different formats as you like. 使用
coalesce()
,您可以根据需要选择多种格式。
You can use TRY_PARSE or PARSE to parse the date literal using a specific culture. 您可以使用TRY_PARSE或PARSE使用特定区域性来解析日期文字。
The second format YYYY-MM-DD
is an unambiguous date format for the "new" date types like date
and datetime2
. 第二种格式
YYYY-MM-DD
是“新”的日期类型,如一个明确的日期格式date
和datetime2
。 It's not affected by the DATEFORMAT
setting like datetime
. 它不受
datetime
等DATEFORMAT
设置的影响。
This means you only need to find one culture that can handle the first format. 这意味着您只需要找到可以处理第一种格式的文化即可。 All of the following queries will return the same value :
以下所有查询将返回相同的值:
select parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
select try_parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select try_parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
If you are on SQL 2012 and above, you can use the FORMAT function. 如果您使用的是SQL 2012及更高版本,则可以使用FORMAT函数。
The signature of this function is - FORMAT (value,format[,culture])
该函数的签名是
FORMAT (value,format[,culture])
Example: SELECT FORMAT (getdate(), 'dd-MM-yyyy') as date
and in your case SELECT FORMAT(CAST(<str_value> as DATE), 'yyyy-mm-dd')
示例:
SELECT FORMAT (getdate(), 'dd-MM-yyyy') as date
,在您的情况下为SELECT FORMAT(CAST(<str_value> as DATE), 'yyyy-mm-dd')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.