尝试转换为日期时间时避免错误
Avoid errors when attempting to convert to datetime
SQL 中是否有一种方法可以忽略转换失败的记录。设置一些默认值也可以。
> SELECT convert(datetime, foo_str)
> FROM foo_tbl
------------------------
Aug 23 2013 00:00:00.000
Aug 17 2013 00:00:00.000
May 06 2015 00:00:00.000
Aug 13 2013 00:00:00.000
Aug 09 2013 00:00:00.000
Sep 05 2007 00:00:00.000
May 06 2015 00:00:00.000
May 06 2015 00:00:00.000
Feb 24 2009 00:00:00.000
May 06 2015 00:00:00.000
Mar 29 2013 00:00:00.000
May 06 2015 00:00:00.000
Jul 24 2010 00:00:00.000
May 06 2015 00:00:00.000
May 06 2015 00:00:00.000
May 03 2015 00:00:00.000
Msg 249, Level 16, State 1 , Line 1 Syntax error during explicit
conversion of VARCHAR value '10101' to a DATETIME field.
是否可以避免错误,从而使 SELECT 语句完成?
类似下面的代码应该可以在 sybase 上运行
SELECT convert(datetime, foo_str)
FROM foo_tbl
WHERE foo_str like '[A-Z][A-Z][A-Z] [0-1][0-9] [0-2][0-9][0-9][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9][0-9][0-9]'
如果 00:00:00.000
是常量你可以做得更简单
SELECT convert(datetime, foo_str)
FROM foo_tbl
WHERE foo_str like '[A-Z][A-Z][A-Z] [0-1][0-9] [0-2][0-9][0-9][0-9] 00:00:00.000'
或
SELECT convert(datetime, foo_str)
FROM foo_tbl
WHERE foo_str like '[A-Z][A-Z][A-Z] [0-1][0-9] [0-2][0-9][0-9][0-9]%'
SQL 中是否有一种方法可以忽略转换失败的记录。设置一些默认值也可以。
> SELECT convert(datetime, foo_str)
> FROM foo_tbl
------------------------
Aug 23 2013 00:00:00.000
Aug 17 2013 00:00:00.000
May 06 2015 00:00:00.000
Aug 13 2013 00:00:00.000
Aug 09 2013 00:00:00.000
Sep 05 2007 00:00:00.000
May 06 2015 00:00:00.000
May 06 2015 00:00:00.000
Feb 24 2009 00:00:00.000
May 06 2015 00:00:00.000
Mar 29 2013 00:00:00.000
May 06 2015 00:00:00.000
Jul 24 2010 00:00:00.000
May 06 2015 00:00:00.000
May 06 2015 00:00:00.000
May 03 2015 00:00:00.000
Msg 249, Level 16, State 1 , Line 1 Syntax error during explicit conversion of VARCHAR value '10101' to a DATETIME field.
是否可以避免错误,从而使 SELECT 语句完成?
类似下面的代码应该可以在 sybase 上运行
SELECT convert(datetime, foo_str)
FROM foo_tbl
WHERE foo_str like '[A-Z][A-Z][A-Z] [0-1][0-9] [0-2][0-9][0-9][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9][0-9][0-9]'
如果 00:00:00.000
是常量你可以做得更简单
SELECT convert(datetime, foo_str)
FROM foo_tbl
WHERE foo_str like '[A-Z][A-Z][A-Z] [0-1][0-9] [0-2][0-9][0-9][0-9] 00:00:00.000'
或
SELECT convert(datetime, foo_str)
FROM foo_tbl
WHERE foo_str like '[A-Z][A-Z][A-Z] [0-1][0-9] [0-2][0-9][0-9][0-9]%'