Why does this statement succeed?
SELECT CAST('08:50' as time)
But this one fails? tmrec is an nvarchar(6) column and contains the same value '08:50'. This is making me crazy since last 1 hour.
SELECT TOP 1 CAST(tmrec as time)
FROM Instr
WHERE igrp = 'JD'
ORDER BY ino , smallin
This screenshot shows the 1st query’s result. It contains 08:50. Yet the 2nd query throws error.
Edit:
Even this doesn’t work which guarantees that conversion is applied only on fetched records:
SELECT CAST( tmrec as time)
FROM
(
SELECT TOP 1 tmrec
FROM [ccwise-courts].[dbo].[INSTR]
WHERE igrp = 'JD'
ORDER BY ino , smallin
) v
Generally, to look for bad data, you can use a query like this:
And if you still cannot make it out, you can list out the specific ASCII code of the characters involved (here I go up to 6 per the question):
There is this Connect item that deals with SQL Server processing CAST on the SELECT clause before the WHERE filter has been applied. To overcome that, as also noted in the bug report, you can use a CASE statement: