Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine MAX Decimal Scale Used on a Column

In MS SQL, I need a approach to determine the largest scale being used by the rows for a certain decimal column.

For example Col1 Decimal(19,8) has a scale of 8, but I need to know if all 8 are actually being used, or if only 5, 6, or 7 are being used.

Sample Data:

123.12345000
321.43210000
5255.12340000
5244.12345000

For the data above, I'd need the query to either return 5, or 123.12345000 or 5244.12345000.

I'm not concerned about performance, I'm sure a full table scan will be in order, I just need to run the query once.

like image 681
Bo Flexson Avatar asked Jan 23 '12 20:01

Bo Flexson


People also ask

How do you find the maximum value of a decimal?

So for decimal(5,2) it would be 999.99 . 5 is the total number of decimals to the left and to the right of the decimal point. 2 is the number of decimals to the right of the decimal point. The maximum possible range for decimals is -10^38 + 1 through 10^38 - 1.

How do you find the Max decimal places in SQL?

The maximum total number of decimal digits to be stored. This number includes both the left and the right sides of the decimal point. The precision must be a value from 1 through the maximum precision of 38. The default precision is 18.

What is the maximum precision for the decimal data type?

The position of the decimal point is determined by the precision and the scale of the number. The scale, which is the number of digits in the fractional part of the number, cannot be negative or greater than the precision. The maximum precision is 31 digits.

How do I get the decimal part of a number in SQL?

X - TRUNC(X), works for negatives too. It would give you the decimal part of the number, as a double, not an integer.


2 Answers

Not pretty, but I think it should do the trick:

-- Find the first non-zero character in the reversed string...
-- And then subtract from the scale of the decimal + 1.
SELECT 9 - PATINDEX('%[1-9]%', REVERSE(Col1))
like image 154
Michael Fredrickson Avatar answered Sep 17 '22 17:09

Michael Fredrickson


I like @Michael Fredrickson's answer better and am only posting this as an alternative for specific cases where the actual scale is unknown but is certain to be no more than 18:

SELECT LEN(CAST(CAST(REVERSE(Col1) AS float) AS bigint))

Please note that, although there are two explicit CAST calls here, the query actually performs two more implicit conversions:

  1. As the argument of REVERSE, Col1 is converted to a string.

  2. The bigint is cast as a string before being used as the argument of LEN.

like image 40
Andriy M Avatar answered Sep 18 '22 17:09

Andriy M