I have a simple CTE that pulls dates from a table - the dates (ApptDateTime
) are stored in YYYY-MM-DDZHH:mm:SS
format. Some columns have NULL values, so I want to ignore them, along with anything that isn't really a date.
If I do:
;WITH cte
AS
(SELECT
urn,
CONVERT(DATETIME, ApptDateTime) AS ApptDateTime
FROM data
WHERE ISDATE(ApptDateTime) = 1
)
SELECT
*
FROM cte
ORDER BY ApptDateTime
... this works fine; I get a list of records back, ordered by date. However, if I want to see only dates that are before today and introduce a WHERE
:
;WITH cte
AS
(SELECT
urn,
CONVERT(DATETIME, ApptDateTime) AS ApptDateTime
FROM data
WHERE ISDATE(ApptDateTime) = 1
)
SELECT
*
FROM cte
WHERE ApptDateTime < GETDATE()
ORDER BY ApptDateTime
I get the error
Conversion failed when converting date and/or time from character string.
I can't see any dodgy non-date, non-NULL values in the table, and even if there were I'd expect anything that wasn't able to be CONVERT
ed to cause an issue as part of the SELECT
in the CTE. However, it only throws that error when I'm trying to compare the datetime. This seems so simple that I'm certain I'm missing something blindingly obvious - but I can't see it.
EDIT: If I send the results to a temp table, and then do the comparison on that ... it works fine!
SELECT
urn,
convert(datetime,ApptDateTime) as ApptDateTime
into #temp FROM data
WHERE ISDATE(ApptDateTime) = 1
SELECT
*
FROM #temp
WHERE ApptDateTime < getdate()
ORDER BY ApptDateTime
DROP TABLE #temp