开发者

SQL Server Datetime Subquery Conversion Error?

开发者 https://www.devze.com 2023-01-30 00:19 出处:网络
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 (which has clean dates) back to

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 (which has clean dates) back to a datetime for the where clause. I've included a tableless example which fails. Spent a long time on this thus far - hating life.

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'


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'
0

精彩评论

暂无评论...
验证码 换一张
取 消