我有以下数据集:
CISS_STATUS SVCDAT BRANCD
. 68
. 68
R . 68
R . 68
. 68
. 68
. 22
R 01/01/2013 65
A 01/01/2014 22
A 01/01/2015 32
大约有500K记录和60个其他字段,但是你明白了。无论如何,我想要做的是编写一个WHERE子句,它根据SVCDAT(这是一个VarChar(10)数据类型)排除其中没有有效日期的记录(即带有点的记录)。 / p>
当我尝试类似的事情时:
WHERE convert(datetime,SVCDAT,1) > '1/1/1900'
我收到此错误:
Conversion failed when converting date and/or time from character string.
当我尝试这个时:
WHERE CAST(SVCDAT as smalldatetime) > '1/1/1900'
我收到此错误:
The conversion of a varchar data type to a smalldatetime data type resulted in
an out-of-range value.
有人对如何解决这个问题有任何想法吗?
答案 0 :(得分:4)
由于您使用的是SQL Server 2012,因此可以使用TRY_CONVERT
。如果无法转换该值,则返回NULL:
WHERE TRY_CONVERT(datetime, SVCDAT, 1) > '1/1/1900'
更多信息here。
答案 1 :(得分:1)
使用ISDATE()
功能过滤坏数据。然后使用where子句中的过滤器来过滤大于给定日期的记录
select * from
(
select *
from yourtable
where ISDATE(SVCDAT) = 1
) a
where convert(date,SVCDAT) > convert(date,'1/1/1900')
或使用TRY_CAST
功能
select * from
(
select *
from yourtable
where try_cast(SVCDAT as date) is not null
) a
where convert(date,SVCDAT) > convert(date,'1/1/1900')