尝试转换为datetime

时间:2015-05-14 08:32:59

标签: sql tsql sybase

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
  

消息249,级别16,状态1,行1显式期间语法错误   转换VARCHAR值' 10101'到DATETIME字段。

可以避免错误,以便SELECT语句完成吗?

1 个答案:

答案 0 :(得分:2)

以下代码之类的东西应该适用于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]%'