use 'between' with varchar (sql server)

后端 未结 3 1141
走了就别回头了
走了就别回头了 2021-01-20 10:33

Using SQL Server 2005 Express.

(
    CONVERT(VARCHAR(8), R.reviewStart, 108) between CONVERT(VARCHAR(8), M.meetingStart, 108) and CONVERT(VARCHAR(8), M.meeti         


        
相关标签:
3条回答
  • 2021-01-20 10:42

    As I said in your other post if is possible you should consider moving to SQL 2008 because of the new datetime types that allow explicit separation of date part and time part so your filter expressions become much simpler and you can index by time. Since its Express there really shouldn't be any reason to hold you back at 2005.

    0 讨论(0)
  • 2021-01-20 10:54

    Yes, depending on what you mean by expected behavior. The BETWEEN operator will treat these operands as varchars, and apply its comparison rules accordingly:

    BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

    Now, I can see a lot of potential problems, comparing strings and expecting date comparison behavior. I haven't seen any in my tests, but look carefully at your data. Is the CONVERT returning 24-hour time, with the appropriate leading zeroes?

    This question has some other approaches to comparing dateless-times, other than converting them to varchars.

    Also, watch for null dates, which will cause the corresponding WHERE condition to return false (actually, unknown).

    In your other question, you indicated that you were getting an error. If so, can you post that?

    0 讨论(0)
  • 2021-01-20 11:01

    Your first condition is equivalent to this more index friendly one:

    R.reviewStart >=  DATEADD(day, DATEDIFF(day, '19010101', M.meetingStart), '19010101') 
    and R.reviewStart < DATEADD(day, 1+DATEDIFF(day, '19010101', M.meetingStart), '19010101') 
    

    (explained here: Reuse Your Code with Table-Valued UDFs ) .

    0 讨论(0)
提交回复
热议问题