1

Is there a way (aside from casting i to something like a bigint) to avoid the arithmetic overflow error in the following set of statements?

DECLARE @tbl TABLE ( [i] INT );

INSERT  INTO @tbl
        ( [i] )
VALUES  ( POWER(2, 30) ),
        ( POWER(2, 30) );

SELECT  SUM([t].[i])
FROM    @tbl AS [t];

I tried a TRY_CAST() on the SUM() but it seems that the error is happening before that point. I'm fine if a NULL (or any other value) gets returned on an overflow.

0

1 Answer 1

3

Casting to bigint before the aggregate then try_casting the result back to int would be preferable to me

But a way without that is

SET ARITHABORT OFF
SET ANSI_WARNINGS OFF

  DECLARE @tbl TABLE ( [i] INT );

    INSERT  INTO @tbl
            ( [i] )
    VALUES  ( POWER(2, 30) ),
            ( POWER(2, 30) );

    SELECT  SUM([t].[i])
    FROM    @tbl AS [t];

SQL Fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

It is important to note that Setting ARITHABORT to OFF can negatively impact query optimization leading to performance issues. You should really be looking for another way to avoid arithmetic overflow.
@TT. it prevents indexed views and indexes on computed columns being matched but it doesn't have any other negative effects on query optimisation if those aren't being used. The warning in the article is about having mismatched values for this setting making troubleshooting more difficult, as different sessions with different values for these options can't share each other's plans so it is possible to have a parameter sniffing issue that only happens to show up in the plan used by the application then running in SSMS all works fine.
@MartinSmith You wouldn't happen to know of an official link for that, would you? I'm always interested in knowing about such thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.