无法理解为什么当我的子查询正确过滤掉坏日期数据(用户在真实查询中输入)但是当我将子查询(具有干净日期)的结果转换回日期时间时查询失败条款。我已经包含了一个失败的无表格示例。花了很长时间来讨论这种令人讨厌的生活。
select
date_test
from
(
select
date_test
from
(
select
'01/01/1980' as date_test
union select
'a'
) as qry_bad_date
where
ISDATE(date_test) = 1
) as qry_only_valid_date
where
cast(date_test as datetime) = '01/01/1980'
答案 0 :(得分:1)
如果您正在使用查询分析器,请转到“查询”菜单并选择“显示估计的执行计划”,或按CTRL + L. Sql Server的查询优化器已经决定将date_test与您指定的日期进行比较属于食物链上的更高。如果将ISDATE检查添加到where子句中,则可以正常工作:
select date_test
from (select date_test
from (select '1980/01/01' as date_test
union
select 'a'
) as qry_bad_date
where ISDATE(date_test) = 1
) as qry_only_valid_date
where ISDATE(date_test) = 1 and cast(date_test as datetime) = '1980/01/01'
如果使用临时表或表变量强制查询单独执行,它也可以工作:
declare @dt1 table (date_test varchar(20))
declare @dt2 table (date_test varchar(20))
insert @dt1 select '1980/01/01' union select 'a'
insert @dt2 select date_test from @dt1 where ISDATE(date_test) = 1
select date_test
from @dt2
where cast(date_test as datetime) = '1980/01/01'
答案 1 :(得分:0)
看起来这也有效。谢谢你的帮助!
select
date_test
from
(
select
case isdate(date_test) when 1 then CAST(date_test as datetime) else null end as date_test
from
(
select
'1980/01/01' as date_test
union select
'a'
) as qry_bad_date
where
ISDATE(date_test) = 1
) as qry_only_valid_date
where
cast(date_test as datetime) = '1980/01/01'