I like CTE for this, or you can also do temp tables, variable tables, or an embedded view such as @Derek.
Basically, we will first take the correct data type and then create our query much easier:
;with CTE as ( -- Bring back the column as datetime select case when isdate(UTC_Time_Stamp) = 1 then cast(UTC_Time_Stamp as datetime) end as UTC_Time_Stamp from [Table] ) -- Simple select with the proper datatype select convert(varchar(50), UTC_Time_Stamp, 127) as [TimeStamp] from CTE -- May still need gt and lt functionality where UTC_Time_Stamp between cast('11/09/2012' as datetime) and cast('11/10/2012' as datetime)
It seems that you use arbitrarily small and large values ββfor TimeStamp when you have non-dates, which is probably not necessary when comparing, so I deleted them.
Note that I use the datetime data type in CTE and for comparison, only converting it to a string for presentation.
Also note that between included, so you may need to return to a separate sentence > and < where.
source share