Continue running SQL even after an error in where clause

Kunder, Santhosha SBOBNG-PTIV/ES 86 Reputation points
2022-12-18T06:18:40.117+00:00

All,

The last statement in this code block gives me the DATE conversion error. My requirement is to run the statement even after the last statement fails. How can I achieve this?

SELECT USERID FROM IMSIDENTITYPRE   
WHERE IDENTITYSTATUS IN ('ACTIVATED','INITIATED','SUSPENDED')      
AND AUTHORITATIVESOURCE IN('WD', 'SP' )          
AND USERID NOT IN (SELECT IDENTITYUSERID FROM WDIdentityPRE)      
AND USERID NOT IN (SELECT GDD FROM ADIdentityPRE)  
AND CAST(AssignmentStartDate AS DATE)<=GETDATE()  
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,492 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,708 questions
0 comments No comments
{count} votes

Accepted answer
  1. Dan Guzman 9,401 Reputation points
    2022-12-18T09:25:45.8+00:00

    Adding to @Viorel 's answer, TRY_CAST (or TRY_CONVERT) will return NULL when the proported date column value cannot be converted to date. The predicate TRY_CAST(AssignmentStartDate AS DATE)<=GETDATE() will not be satisfied for invalid dates because the result is UNKNOWN instead of true of false.

    SELECT USERID FROM IMSIDENTITYPRE   
    WHERE  
        IDENTITYSTATUS IN ('ACTIVATED','INITIATED','SUSPENDED')      
        AND AUTHORITATIVESOURCE IN('WD', 'SP' )          
        AND USERID NOT IN (SELECT IDENTITYUSERID FROM WDIdentityPRE)      
        AND USERID NOT IN (SELECT GDD FROM ADIdentityPRE)  
        AND TRY_CAST(AssignmentStartDate AS DATE)<=GETDATE();  
    

    Consider changing the AssignmentStartDate column to a date data type to ensure invalid dates cannot be stored. This will provide data integrity, improve performance, and reduce storage needs.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Viorel 122.2K Reputation points
    2022-12-18T08:15:02.807+00:00

    Use TRY_CAST instead of CAST. The bad rows will be excluded.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.