Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server round after division

In a stored procedure I have an expression like

select @some_val_in_percents = (@total_val / 100) * @some_val

If I use the Round function like this:

select @some_val_in_percents = Round((@total_val / 100) * @some_val, 0)

will the result be rounded when the whole expression is calculated or will (@total_val / 100) be rounded and than multiplied by @some_val?

like image 446
superM Avatar asked Apr 23 '12 10:04

superM


People also ask

How do you ROUND division in SQL?

SQL Server ROUND() Function The ROUND() function rounds a number to a specified number of decimal places.

How do you ROUND to 2 decimal places in SQL?

Using ROUND() function with a variable and getting the rounded number to -2 decimal place.

How do I always ROUND up in SQL?

Use CEILING() function (MS SQL).

How do you ROUND to the next integer in SQL?

ROUND() Function in MySQL. The ROUND() function in MySQL is used to round a number to a specified number of decimal places. If no specified number of decimal places is provided for round off, it rounds off the number to the nearest integer.


2 Answers

You seem to be calculating the percent value wrongly. Here's what I would expect it to be like:

@some_val * 100 / @total_val

As for the ROUND() function, it will act on the final result of the expression, not on the partial result. So, first the expression is evaluated completely, then ROUND() is applied to the result.

Note also (in case you haven't already known it) that if both operands of the division operator are integers, SQL Server will perform an integer division, i.e. the result of the division would be rounded down to the nearest integer even before ROUND() is applied. If you want to avoid that, make sure that at least one of the operands is not integer, e.g. like this:

ROUND(@some_val * 100.0 / @total_val, 2)

Note also the second argument (precision), which is required in Transact-SQL ROUND().

like image 66
Andriy M Avatar answered Sep 30 '22 20:09

Andriy M


Round will be calculated after its contents is evaluated.

Therefore (@total_val / 100) * @some_val will be rounded.

like image 30
Curtis Avatar answered Sep 30 '22 20:09

Curtis