SQL Server Datetime Subquery Conversion Error?

时光怂恿深爱的人放手 提交于 2019-12-18 09:54:35

问题


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'

回答1:


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'



回答2:


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'


来源:https://stackoverflow.com/questions/4384709/sql-server-datetime-subquery-conversion-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!