SQL 如何处理SQL中的日期转换错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21422029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:54:53  来源:igfitidea点击:

How to handle date conversion error in SQL?

sqlstringtsqlerror-handlingtype-conversion

提问by sav

So I'm trying to convert strings in an SQL databse into datetime values.

所以我试图将 SQL 数据库中的字符串转换为日期时间值。

I have some dates in a table like this:

我在这样的表格中有一些日期:

23/12/2013 16:34:32
24/12/2013 07:53:44
24/12/2013 09:59:57
24/12/2013 12:57:14
24/12/2013 12:48:49
24/12/2013 13:04:17
24/12/2013 13:15:47
24/12/2013 13:21:02
24/12/2013 14:01:28
24/12/2013 14:02:22
24/12/2013 14:02:51

They are stored as strings unfortunately

不幸的是,它们被存储为字符串

And I want to convert them to datetime

我想将它们转换为日期时间

SELECT CONVERT(datetime, analysed, 103 )
FROM OIL_SAMPLE_UPLOAD

However I get this message when I run the query

但是,当我运行查询时收到此消息

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

将 varchar 数据类型转换为 datetime 数据类型导致值超出范围。

Presumably because some values are badly formed (although I am yet to spot any of these)

大概是因为一些价值观的形成很糟糕(尽管我还没有发现其中的任何一个)

It's ok if some values don't convert, I just need a way of handling this situation.

如果某些值不转换也没关系,我只需要一种处理这种情况的方法。

Something like ISNULL(CONVERT(datetime, analysed, 103 )) would be good except that the convert function does not return NULL when it fails.

像 ISNULL(CONVERT(datetime, Analyzed, 103 )) 这样的东西会很好,只是转换函数在失败时不会返回 NULL。

回答by Mudassir Hasan

For SQL Server you can use ISDATE()function to check whether value is valid date

对于 SQL Server,您可以使用ISDATE()函数来检查值是否为有效日期

SELECT CASE WHEN ISDATE(analysed)=1 THEN CONVERT(datetime, analysed, 103 ) 
            ELSE '' END
FROM OIL_SAMPLE_UPLOAD

回答by Lev Z

You can use TRY_CONVERTor TRY_CASTfunctions

您可以使用TRY_CONVERTTRY_CAST函数

回答by user2989408

If you just want the date part then take a SUBSTRINGand calculate the date as follows. This might get you the correct date part at least.

如果您只想要日期部分,请SUBSTRING按如下方式计算日期。这至少可以为您提供正确的日期部分。

SELECT CONVERT(datetime, SUBSTRING(analysed, 0, 11), 103 )
FROM OIL_SAMPLE_UPLOAD