如何在SQL Server中将“ DD / MM / YYYY”或“ YYYY-MM-DD”中的字符串转换为日期?

hus*_*jid 0 sql sql-server sql-server-2012

我在这里有一个字符串,需要将其转换为日期,但问题是它可能采用'DD / MM / YYYY'或'YYYY-MM-DD'格式。

我已经尝试过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
Run Code Online (Sandbox Code Playgroud)

以上两种解决方案均导致错误,原因是我使用了其他格式。

有什么方法可以将字符串转换为日期,而不管其采用哪种格式?

Gor*_*off 6

用途try_convert()

insert into @table
    select coalesce(try_convert(date, @string, 111),
                    try_convert(date, @string, 103)
                   ) as date
Run Code Online (Sandbox Code Playgroud)

try_convert()NULL如果转换失败,则返回。在这种情况下,转换将继续进行下一个模式。使用coalesce(),您可以根据需要选择多种格式。