SQL server doesn't implicitly cast from VARCHAR to FLOAT in some scenarios

Nandu S Raj 105 Reputation points
2024-11-26T14:19:29.5566667+00:00

Update: I have pasted the actual image here instead of the link.

--This works fine
DECLARE @sampleVar FLOAT = '123.034';
SELECT @sampleVar ;

--This throws error
SELECT '123.034'*-1;

When I try to do the above, I notice that the implicit CAST is happening for variable assigment , but I get a cast exception for the last query.

As per the below image which I snipped from MS docs, it says implicit cast is supported.

User's image

Is this inconsistency expected? Also , in the image it says an explicit cast is required to preserve precision - are we referring to CAST function in specific or is it irrespective?

SQL Server | Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Dan Guzman 9,411 Reputation points
    2024-11-26T15:05:48.8466667+00:00

    --This throws error

    SELECT '123.034'*-1;

    The constant -1 is an integer literal so SQL Server attempts to convert the varchar '123.034' value to integer per data type precedence rules. This results in an error due the fractional value.

    Specify float constant to avoid the error:

    SELECT '123.034'*-1E0;

    1 person found this answer helpful.

  2. LiHongMSFT-4306 31,616 Reputation points
    2024-11-27T03:17:40.7166667+00:00

    Hi @Nandu S Raj

    So the presence of integer '-1' forces sql server to try and convert the varchar constant to integer, but it fails to do so why?

    The reason is a varchar value could contain characters not just numeric values. It is hard to build a logic to handle the convert behavior.

    As we know, not only a varchar like '123.800' to an int but also these conversations: varchar 'A123' or '123.8,123.6' to int will be failed. SQL Server doesn't know how to handle the non-numeric characters or decimals in a varchar string.

    However, when converting between numeric types like float or decimal to int, the logic is simple, SQL Server will just truncate the decimal part because it knows it is safe to remove the decimal part.

    Therefore, when trying to convert a varchar to int, SQL Server expects the varchar to contain only solid int values.

    Best regards,

    Cosmog


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".


Your answer

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