I wrote the following query to obtain a date, remove it’s time part and add the time I wanted.
If I run this query without the TOP clause, it works well. But when I add it, it returns the following exception: “Conversion failed when converting date and/or time from character string.”
Here is the query:
SELECT TOP 1
CONVERT(DateTime, (CONVERT(varchar(50),CONVERT(Date, VRSAS.EventOn))
+ ' ' +
CONVERT(varchar(50), CONVERT(Time, '23:30')))) E
FROM ViewRangeSheetActualStatus VRSAS
Where VRSAS.EventOn <= '2010-07-31'
AND VRSAS.[Status] = 1
order by VRSAS.RangeSheet
The field EventOn is of type DateTime.
What could be going on?
I’ve reproduced quite easily this end. I found using
DATEADDresolved itBut I’m not actually sure why yet. Steps to reproduce below.
Looking at the
ComputeScalarproperties in the execution plan the two are different.All
Top 1
Before the final conversion to
datetimethe first one produces a varchar containing the followingThe second version produces a varchar containing
It is the
.0000000that causes the problem casting back todatetime. I have no idea why the addition ofTOPto the query would cause this completely unrelated change in behaviour.