Can\'t comprehend why when my subquery properly filters out bad date data (user entered in real query) but that the query fails when I cast the results of the subquery (whic
If you're using Query Analyzer, go to the Query menu and select 'Display estimated execution plan', or hit CTRL+L. Sql Server's query optimizer has decided that comparing date_test to your specified date belongs higher on the food chain. If you add the ISDATE check to your where clause it works fine:
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'
If you use temp tables or table variables to force the queries to execute separately it also works:
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'
Looks like this works too. Thanks for all the help!
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'