If you use the Query Analyzer, go to the Query menu and select "Show Estimated Execution Plan" or press CTRL + L. Query Optimizer Sql Server decided that comparing date_test with the specified date refers to the food chain above. If you add an ISDATE check to your where statement, it will work 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 temporary tables or variable tables to force queries, 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'
source share