Been searching for an hour and can't find an answer that addresses what's happening with my code. This query happily returns data:
WITH RESULTS_TEST_COMPONENT_CTE(RequisitionNumber, ResultsName, ResultValue)
AS
(
SELECT [RequisitionNumber]
,[ResultsName]
,LTRIM(RTRIM([ResultValue]))
FROM dbo.RESULTS_TEST_COMPONENT
--WHERE TestGroupNumber IN ('T4367', 'T8033')
WHERE SUBSTRING(RequisitionNumber, 2, 4) = '1521'
AND ResultsName = 'HEMOGLOBIN A1C'
AND ISNUMERIC(ResultValue) = 1
)
, RESULTS_TEST_COMPONENT_CTE2(RequisitionNumber, ResultsName, ResultValue)
AS
(
SELECT RequisitionNumber
,ResultsName
,CAST(ResultValue AS decimal(3,1)) AS ResultValue
FROM RESULTS_TEST_COMPONENT_CTE
)
SELECT * FROM RESULTS_TEST_COMPONENT_CTE2
Here are the first few rows of data, just as expected:
RequisitionNumber ResultsName ResultValue
C1521020510 HEMOGLOBIN A1C 5.9
C1521044250 HEMOGLOBIN A1C 5.4
C1521123010 HEMOGLOBIN A1C 5.6
C1521121420 HEMOGLOBIN A1C 5.8
C1521102210 HEMOGLOBIN A1C 13.2
However, when I change the last line to this, it throws an "Arithmetic overflow error converting varchar to data type numeric." error:
SELECT * FROM RESULTS_TEST_COMPONENT_CTE2
WHERE CAST(ResultValue AS decimal(3,1)) BETWEEN 7.5 AND 10
I also get the error if I leave out the "CAST" and just put WHERE ResultValue BETWEEN 7.5 AND 10. I have confirmed that all the data in the ResultValue column is numeric in the format 00.0. I need that WHERE clause to fulfill the requirement that the value be >=7.5 and <=10. I expected it to return that last row where ResultValue is 13.2, but instead I get that error. Can anyone tell me what the problem is?
(I also get the error if I use just the first CTE.)

