T-SQL:检查Where-Clause中的日期是否格式正确

时间:2015-06-05 08:16:42

标签: sql tsql select where

如何设置date参数,如果设置了date参数以及它是否采用了正确的格式(dd/mm/yyyy),如何检查。

以下是我的SP参数@birthdaysearch,格式为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

为什么不起作用?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

语法不正确:

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

或:

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

但为什么要将日期与LIKE进行比较,这很奇怪? 我建议你:

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

答案 1 :(得分:-1)

鉴于评论中的对话,我认为以下是适当的:

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

因此,假设您的参数是日期时间类型且可以为空,则无需检查日期格式,因为它在到达sproc时始终有效(或为null)。