如何在插入时在INT列上使用SUM时防止算术溢出错误?

时间:2018-04-12 11:18:48

标签: sql-server

我的问题类似于中的问题 How to prevent arithmetic overflow error when using SUM on INT column?但限制了int值。

如果sum(column_name)超出int限制,我想插入int的最大限制(2147483647),怎么做?注意:TotalExp数据类型为INT

INSERT INTO NEWTABLE
SELECT    UserId,
          SUM( PokemonExp )     AS TotalExp,
          MAX( PokemonLevel )   AS MaxPokeLevel
FROM      mytable
GROUP BY  UserId
ORDER BY  TotalExp DESC

1 个答案:

答案 0 :(得分:0)

将PokemonExp转换为bigint

INSERT INTO NEWTABLE
SELECT
  UserId,
  CASE WHEN 
    SUM( CAST(PokemonExp as BIGINT)) > 2147483647
         THEN 2147483647 
         ELSE SUM( CAST(PokemonExp as BIGINT))
         END AS TotalExp,
  MAX( PokemonLevel ) AS MaxPokeLevel
FROM      mytable
GROUP BY  UserId
ORDER BY  TotalExp DESC