过滤掉错误的日期值

时间:2014-01-20 16:15:49

标签: sql-server sql-server-2008

我在SQL Server中有一个表来获取数据并将expirationDate(varchar(4000))转换为DATE

此表格由Excel工作表填充,这就是它具有不同日期的原因。

我需要以某种方式将所有这些格式转换为一种格式,并使用DATE语句转换为SELECT

expirationDate中的示例数据:

2099-09-09
NULL
NA
8/25/12
12/21/11
na
2010-11-07
2013-10-07
NULL
3/25/12
tbd
NA
N/A
2009-04-17
2011-02-21
02/15/2011
08/31/11
NULL
2012-11-06
na
2011-12-21
2011-10-09
NA
2009-04-17
NA
2/29/12

我试过了:

select CASE WHEN ISDATE(expirationDate) = 1 THEN CAST(expirationDate AS DATE) 
       ELSE cast(null as DATE) END
 FROM [dbo].[ComponentData]

但是它引发了错误:

Conversion failed when converting date and/or time from character string.

我也尝试过:

CONVERT(varchar(4000),CAST(expirationDate AS DATE),100)

但同样的事情...... :(

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

我明白了:

测试:

select CAST(REPLACE(CONVERT(NVARCHAR, componentExpirationDate,103), '/', '-') as date)
 from [dbo].[BatchComponent]
 where ISDATE(componentExpirationDate) = 1

输出:

2099-09-09
2012-01-11
2010-09-27
2012-08-25
2011-12-21
2010-09-01
2016-02-02
2009-05-08
2010-11-07
2013-10-07

更改为CASE WHEN:

select CASE WHEN ISDATE(expirationDate) = 1 THEN CAST(REPLACE(CONVERT(NVARCHAR, expirationDate,103), '/', '-') as date) 
        ELSE cast(null as date) END
     FROM [dbo].[ComponentData]

谢谢大家的帮助。