Multiple CASTs WHY?

2021-09-22T16:57:11.953+00:00

I am starting a new job working with some previous SSRS reports and the person previous to me has, in the dataset SQL, several spots where they have

CAST(SUM(CAST(MyFieldNameHere As Decimal(21,4))) As Decimal(21,4))

The original field is Decimal(19,4) in the table but I don't see why they would have to cast it twice to 21,4. Any good reason that anyone can think of?

We're using SQL 2017 or 2017 Compatibility, not sure exactly.

SQL Server Reporting Services
SQL Server Reporting Services
A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.
2,807 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,555 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tom Cooper 8,466 Reputation points
    2021-09-22T17:37:41.823+00:00

    You don't need both CAST's. The interior cast will not change the final result in any way. So you just need
    CAST(SUM(MyFieldNameHere) AS Decimal(21,4))

    The SUM documentation at https://learn.microsoft.com/en-us/sql/t-sql/functions/sum-transact-sql?view=sql-server-ver15 states that the return type of a SUM of a decimal(p,s) will be decimal(38,s). So changing the type before the sum from decimal(19,4) to decimal(21,4) won't change the result.

    Tom

    0 comments No comments

0 additional answers

Sort by: Most helpful