Why cast/convert from int returns an asterisk

前端 未结 2 561
名媛妹妹
名媛妹妹 2020-12-03 01:07

Someone recently asked me this question and I thought I\'d post it on Stack Overflow to get some input.

Now obviously both of the following scenarios are supposed to

相关标签:
2条回答
  • 2020-12-03 01:19

    For even more fun, try this one:

    DECLARE @i INT
    SET @i = 100
    SELECT CAST(@i AS VARCHAR(2)) -- result: '*'
    go
    
    DECLARE @i INT
    SET @i = 100
    SELECT CAST(@i AS NVARCHAR(2)) -- result: Arithmetic overflow error
    

    :)


    The answer to your query is: "Historical reasons"

    The datatypes INT and VARCHAR are older than BIGINT and NVARCHAR. Much older. In fact they're in the original SQL specs. Also older is the exception-suppressing approach of replacing the output with asterisks.

    Later on, the SQL folks decided that throwing an error was better/more consistent, etc. than substituting bogus (and usually confusing) output strings. However for consistencies sake they retained the prior behavior for the pre-existing combinations of data-types (so as not to break existing code).

    So (much) later when BIGINT and NVARCHAR datatypes were added, they got the new(er) behavior because they were not covered by the grandfathering mentioned above.

    0 讨论(0)
  • 2020-12-03 01:29

    You can read on the CAST and CONVERT page on the "Truncating and Rounding Results" section. Int, smallint and tinyint will return * when the result length is too short to display when converted to char or varchar. Other numeric to string conversions will return an error.

    0 讨论(0)
提交回复
热议问题