convert returns conversion error but try_convert does return the correct value

hans smeets 20 Reputation points
2024-06-17T04:41:27.08+00:00

Hi All,

I have the following case statement in a TSQL script, which returns the correct negative decimal value, in the rows that acually have a value

    try_convert (decimal (18,6), max (case
        when [databody.daysQuality.testResults.testType] = 'Freezing Point' and [databody.daysQuality.testResults.testType] is not null
        then [databody.daysQuality.testResults.value]
        else ''
    end)) as [freezing_point]

However, when I change try_convert to convert it will fail with : "Error converting data type varchar to decimal"

Am I missing something here?

Cheers

Hans

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,651 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 112.7K Reputation points MVP
    2024-06-20T22:13:55.48+00:00

    Well, this fails:

    SELECT convert(decimal(18, 6), '')
    

    Not sure why you have that ELSE there. I would think that returning NULL would be better. But I don't know your business rules. Anyway, the empty string seems out of place.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 112.7K Reputation points MVP
    2024-06-17T21:46:20.2033333+00:00

    We only see a snippet of your code, so we are left to guesses.

    However, a common situation is like in this example:

    SELECT a, convert(int, strcol)
    FROM   tbl 
    WHERE  rowtype = 6
    

    And for rowtype = 6, all values in strcol are integer values. Whereas for rowtype = 4 there are strings, rowtype = 5 there are dates etc.

    So logically, this query should not fail. However, the optimizer may get the idea to perform the conversion before filtering for the WHERE clause and the query dies with a conversion error. Changing to try_convert avoids this problem.

    Could this apply to your case?


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.