Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this TSQL cast datetime -> varchar -> datetime?

Tags:

tsql

casting

I recently came across this:

SELECT
    'Y',
    ltrim(rtrim(upper(Newly_Eligible)))
FROM Table
WHERE 
    Id = 1
AND
    (Convert(datetime, Convert(varchar, GETDATE(),103),103)  
    BETWEEN
        Convert(datetime,Convert(varchar, [Start_Date],103),103)
    AND
        Convert(datetime, Convert(varchar, [End_Date] ,103),103))

Start_Date, End_Date and obviously GETDATE() are all datetime types. Why does he cast to a varchar and then back again?

like image 621
sennett Avatar asked Dec 28 '22 02:12

sennett


1 Answers

This truncates any excess time-of-day value out of the datetime leaving just the date value. (The key is the conversion code "103".)

like image 181
RBarryYoung Avatar answered Mar 16 '23 03:03

RBarryYoung