All we need is an easy explanation of the problem, so here it is.
I have a column called
Source in my table called
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.
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
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 |
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂