简体   繁体   中英

T-SQL: Check if date is in proper format within Where-Clause

How is it possible to check within the where-clause, if the date parameter is set and if it's in the proper format ( dd/mm/yyyy ).

Here is my SP with parameter @birthdaysearch in format ( dd/mm/yyyy ):

Select *
From Clients as c
WHERE
    CASE ISDATE(@birthdaysearch)
        WHEN 0 THEN (c.BirthDay LIKE '%')
        WHEN 1 THEN (c.BirthDay LIKE CONVERT(datetime,@birthdaysearch,103))
    END

Why isn't that working?

Thanks for your help!

You have incorrect syntax:

Select *
From Clients as c
WHERE ISDATE(@birthdaysearch) = 0 OR 
      (ISDATE(@birthdaysearch) = 1 AND c.BirthDay LIKE CONVERT(datetime, @birthdaysearch, 103))

or:

Select *
From Clients as c
WHERE c.BirthDay LIKE CASE WHEN ISDATE(@birthdaysearch) = 0 THEN '%'                   
                           ELSE CONVERT(datetime, @birthdaysearch, 103) END

But it is very strange why are you comparing dates with LIKE ? I suggest you the following:

Select *
From Clients as c
WHERE c.BirthDay = CASE ISDATE(@birthdaysearch) WHEN 0 THEN c.BirthDay
                    ELSE CAST(@birthdaysearch AS DATE) END

Given the conversation in the comments, I think the following would be appropriate:

Select *
From Clients as c
WHERE COALESCE(@BirthDaySearch, c.BirthDay) = c.BirthDay

So, given that your parameter is a datetime type, and is nullable, there is no need to check the date format, as it will always be valid (or null) when it hits the sproc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM