SQL - safely downcast BIGINT to INT

前端 未结 4 965
栀梦
栀梦 2020-12-11 03:13

I have a CSV I\'m importing into our database. One of the \"columns\" contains data that should be an INT but some rows have numbers that only fall in the BIGINT ra

4条回答
  •  天命终不由人
    2020-12-11 03:30

    Cast your bigint to varbinary, then store the lower half to @UserID and check the upper half:

    • if the upper half is all 0's and the lower half represents a non-negative value, @UserID then contains the correct int value;

    • if the upper half is all 1's and @UserID is negative, it's all right too;

    • otherwise there's an arithmetic overflow.

    Here's an implementation:

    DECLARE @UserIDBigInt BIGINT = 9723021913;
    DECLARE @UserID INT, @HighInt INT;
    
    WITH v AS (SELECT CAST(@UserIDBigInt AS varbinary) AS bin)
    SELECT
      @HighInt = SUBSTRING(bin, 1, 4),
      @UserID  = SUBSTRING(bin, 5, 4)
    FROM v;
    
    IF (@HighInt = 0 AND @UserID >= 0 OR @HighInt = -1 AND @UserID < 0) BEGIN
        SELECT 'Handle it as reliable data'
    END
    

提交回复
热议问题