3

In with statement:

WITH queryResult AS
(
    SELECT 
        CONVERT(DATETIME, '2017-12-12 ' + PARTIALDATE) 
    FROM 
        tableA 
    WHERE 
        ISDATE('2017-12-12 ' + PARTIALDATE) = 1
)
....

In this block, I will get exception:

Conversion failed when converting date and/or time from character string.

So I made some changes:

WITH subQueryResult AS
(
    SELECT 
        PARTIALDATE 
    FROM 
        tableA 
    WHERE 
        ISDATE('2017-12-12 ' + PARTIALDATE) = 1
),
queryResult AS
(
    SELECT 
        CONVERT(DATETIME, '2017-12-12 ' + PARTIALDATE) 
    FROM 
        subQueryResult
)

And it works!

But why?

10
  • What is the datatype of the PARTIALDATE? my guess is.. the second query guarantees that partialdate is a date as non date rows are excluded.. hence the convert works Commented Jan 9, 2018 at 6:08
  • @Harry varchar(100) Commented Jan 9, 2018 at 6:11
  • @Harry but in first SQL text, I have just the same where statement. Commented Jan 9, 2018 at 6:15
  • 1
    If you're using SQL Server 2012 or newer, you could check out the TRY_CAST / TRY_CONVERT commands - they return NULL, if something cannot be converted (instead of throwing an error) Commented Jan 9, 2018 at 6:28
  • I only get this error when the PartialDate is not suitable and ISDATE() clause is not used in the Select statement. So ithe first query seems to be quite OK for my test Commented Jan 9, 2018 at 6:28

1 Answer 1

1

The WHERE does not do the filtering before the conversion takes place. Order of operations is guaranteed for a case statement. The following should work:

WITH queryResult AS
(
    SELECT 
        CASE WHEN ISDATE('2017-12-12 ' + PARTIALDATE) = 1 THEN CONVERT(DATETIME, '2017-12-12 ' + PARTIALDATE) ELSE NULL END
    FROM 
        tableA 
    WHERE 
        ISDATE('2017-12-12 ' + PARTIALDATE) = 1
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.