Most people know that precision is the total number of digits and scale is the number of those digits that appear after the decimal point. And obviously no matter how many digits or decimal places there are, the highest value would be all 9s. For example, a decimal(5, 2) would be 5 total 9s (99999) with 2 decimal places (999.99). But how do you determine that programmatically?
Well, I suppose you could use the REPLICATE() function to repeat the number 9 as a text string and then STUFF() a decimal point into the string at the appropriate place, but that kind of a hacky way to do it. The BOL page refers to the size limits of the max precision with scale of 0 — decimal(38, 0) — as -10^38+1 to 10^38-1. We can easily get the precision part by raising 10 to the power of
- The formula:
- Min = -(Power(10, precision) – 1)/Power(10, scale)
- Max = (Power(10, precision) – 1)/Power(10, scale)
WITH indexcols AS (SELECT object_id, column_id, Min(key_ordinal) AS KeyOrdinal FROM sys.index_columns WHERE key_ordinal > 0 GROUP BY object_id, column_id) SELECT TableName = Object_schema_name(C.object_id) + N'.' + Object_name(C.object_id), ColumnName = C.NAME, DataType = T.NAME, MaxSize = CASE C.user_type_id WHEN 48 THEN 255 WHEN 52 THEN 32767 WHEN 56 THEN 2147483647 WHEN 106 THEN Replicate(9, C.PRECISION - C.scale) + '.' + Replicate(9, C.scale) WHEN 108 THEN Replicate(9, C.PRECISION - C.scale) + '.' + Replicate(9, C.scale) WHEN 127 THEN 9223372036854775807 END, MinSize = -(CASE C.user_type_id WHEN 48 THEN 0 WHEN 52 THEN 32767 WHEN 56 THEN 2147483647 WHEN 106 THEN Replicate(9, C.PRECISION - C.scale) + '.' + Replicate(9, C.scale) WHEN 108 THEN Replicate(9, C.PRECISION - C.scale) + '.' + Replicate(9, C.scale) WHEN 127 THEN 9223372036854775807 END ), CurrentIdentity = Ident_current(Object_schema_name(C.object_id) + N'.' + Object_name(C.object_id)), IdentityIncrement = Ident_incr(Object_schema_name(C.object_id) + N'.' + Object_name(C.object_id)), IndexPosition = CASE WHEN IC.keyordinal = 1 THEN 'Primary' WHEN IC.keyordinal > 1 THEN 'Non-primary' WHEN IC.keyordinal IS NULL THEN 'Not indexed' END FROM sys.columns AS C INNER JOIN sys.types T ON T.user_type_id = C.user_type_id LEFT JOIN indexcols IC ON IC.object_id = C.object_id AND IC.column_id = C.column_id WHERE C.is_identity = 1 AND Objectpropertyex(C.object_id, 'IsUserTable') = 1;
Max And Min Decimal Values – Curated SQL
[…] Robert Davis gives us the formula for the max and min decimal values given a scale and precision: […]