SQL Server:将表达式转换为数据类型bigint的算术溢出错误

时间:2013-12-19 05:26:42

标签: sql-server

以下是我的查询序列:

SELECT
      CASE
         WHEN ((BarCode IS NOT NULL) AND (ExternelBarCode IS NULL)) THEN BarCode
         WHEN ((BarCode IS NULL) AND (ExternelBarCode IS NOT NULL)) THEN CAST(ExternelBarCode AS bigint)
         ELSE ExternelBarCode -- When both exist
      END AS TicketBarCode
...

当我运行它时,我收到以下消息:

  

将表达式转换为数据类型bigint的算术溢出错误。

BarCode的类型为bigint,列ExternelBarCode的类型为varchar(250)

BarCode = 178625624324,
ExternelBarCode = 2015591149641227565492

如何解决此问题?

1 个答案:

答案 0 :(得分:8)

值2,015,591,149,641,227,565,492大于bigint 2 ^ 63-1(9,223,372,036,854,775,807)允许的最大值,因此转换是不可能的。

如果您需要返回一个数值,可以将其强制转换为decimal(38,0)

SELECT
      CASE
         WHEN ((BarCode IS NOT NULL) AND (ExternelBarCode IS NULL)) THEN CAST(BarCode as decimal(38,0))
         WHEN ((BarCode IS NULL) AND (ExternelBarCode IS NOT NULL)) THEN CAST(ExternelBarCode AS decimal(38,0))
         ELSE cast(ExternelBarCode as decimal(38,0)) -- When both exist
      END AS TicketBarCode