SQL Server Datetime Subquery Conversion Error?

前端 未结 2 907
小蘑菇
小蘑菇 2020-12-22 05:55

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

相关标签:
2条回答
  • 2020-12-22 06:28

    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'
    
    0 讨论(0)
  • 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 讨论(0)
提交回复
热议问题