Sql-server – How to CAST a date in a subquery? Currently getting an error: Conversion failed when converting date and/or time from character string

sql server

I have a column called Source in my table called TPR. The Source column is of datatype varchar and contains text like January 2020 and Q3 Completed. When I run a query that only extracts the date-like fields to CAST as dates like so:

SELECT CAST(Source AS DATE) AS Source
FROM TPR
WHERE Source NOT LIKE 'Q3 Completed`

I get the appropriate results. When I place the query above in a subquery to act as a filter like so:

SELECT CaseNumber
FROM TPR
WHERE Source =
     SELECT CAST(Source AS DATE) AS Source
     FROM TPR
     WHERE Source NOT LIKE 'Q3 Completed`

I get the following error:

Conversion failed when converting date and/or time from character string.
Warning: Null value is eliminated by an aggregate or other SET operation.

I've also tried the following but it too failed:

SELECT CaseNumber
FROM TPR
WHERE CAST(Source AS DATE) =
     SELECT CAST(Source AS DATE) AS Source
     FROM TPR
     WHERE Source NOT LIKE 'Q3 Completed`

I don't understand why this is failing.

Best Answer

Use a CTE to get the wanted rows and then do the conversion

If the strings are not a correct format like seen below, you will get an error.

CREATE TABLE TPR(CaseNumber int,Source varchar(100))
GO
INSERT INTO TPR VALUES (1,'Q3 Completed'),(2,'2021/01/01')
GO
WITH CTE AS (
     SELECT Source
     FROM TPR
     WHERE Source NOT LIKE 'Q3 Completed' )
     SELECT CaseNumber
FROM TPR
WHERE Source IN (SELECT Source FROM CTE)
GO
| CaseNumber |
| ---------: |
|          2 |

db<>fiddle here