Why cast/convert from int returns an asterisk

前端 未结 2 567
名媛妹妹
名媛妹妹 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.

提交回复
热议问题