SQL Server NUMERIC/DECIMAL 精度与存储
考虑 MSDN 有关 SQL Server 2008 R2 NUMERIC/DECIMAL 精度存储的说明。
1到9的精度为5字节
10到19的精度为9字节
因此,如果我的业务案例逻辑上需要具有 2 位小数和 5 位精度的数据类型,那么如果我将其定义为 NUMERIC(5, 2),则不会产生实际性能或存储差异 或 NUMERIC(9, 2)。
考虑到我故意忽略的是隐含的检查约束,因为我很可能在限制实际允许范围的列上放置实际的检查约束。
这对索引、查询性能或系统的任何其他方面有影响吗?
Considering what MSDN states regarding SQL Server 2008 R2 storage of NUMERIC/DECIMAL precision.
Precision of 1 to 9 is 5 bytes
Precision of 10 to 19 is 9 bytes
So if my business case logically requires a data type with 2 decimal places and a precision of 5 digits it makes no actual performance or storage difference if I define it as NUMERIC(5, 2) or NUMERIC(9, 2).
One considering I'm intentionally ignoring is the implied check constraint as I'd most likely put an actual check constraint on the column limiting the actual allowed range.
Does this make a difference when it comes to indexes, query performance or any other aspect of the system?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Numeric(5, 2) 允许使用 999.99 以内的数字。如果您尝试将 1000.0 插入其中,则会出现算术溢出。
Numeric(9,2) 允许数字达到并包括 9 999 999.99
请记住,如果您打算对这个值求和,请留出额外的空间,否则您将出现溢出或者需要进行显式转换。
它们占用相同数量的字节。由于它们的存储大小相同,因此它们在数据页、内存、索引、网络传输等方面都是相同的。
正是由于这个原因,我通常会计算出我需要存储什么大小的数字(如果使用numeric),然后增加精度(也许还有比例),这样我就低于存储大小增加的点。
因此,如果我需要存储最多 9900 万个小数位,则为数字 (12,4)。对于相同的存储,我可以有一个数字 (19,6),并在业务用户宣布他们确实需要在其中存储数十亿美元时提供一些安全空间。
Numeric(5, 2) allows numbers up to and including 999.99. If you try to insert 1000.0 into that, you'll get an arithmetic overflow.
Numeric(9,2) allows numbers up to and including 9 999 999.99
Bear in mind that if you plan to ever sum this value, allow extra space, otherwise you'll get an overflow or you'll need to do an explicit cast.
They take up the same number of bytes. Since they're the same storage size, they're the same in the data page, in memory, in indexes, in network transmission, etc.
It's for this reason that I usually work out what size number I need to store (if using numeric), then increase precision (and maybe scale) so that I'm just below the point where the storage size increases.
So if I need to store up to 99 million with 4 decimal places, that would be numeric (12,4). For the same storage, I can have a numeric (19,6) and give some safe space for when the business user announces that they really do need to store a couple billion in there.