Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

前端 未结 12 2257
时光取名叫无心
时光取名叫无心 2020-11-22 03:45

I\'m curious as to whether or not there is a real difference between the money datatype and something like decimal(19,4) (which is what money uses

12条回答
  •  -上瘾入骨i
    2020-11-22 04:04

    Well, I like MONEY! It's a byte cheaper than DECIMAL, and the computations perform quicker because (under the covers) addition and subtraction operations are essentially integer operations. @SQLMenace's example—which is a great warning for the unaware—could equally be applied to INTegers, where the result would be zero. But that's no reason not to use integers—where appropriate.

    So, it's perfectly 'safe' and appropriate to use MONEY when what you are dealing with is MONEY and use it according to mathematical rules that it follows (same as INTeger).

    Would it have been better if SQL Server promoted division and multiplication of MONEY's into DECIMALs (or FLOATs?)—possibly, but they didn't choose to do this; nor did they choose to promote INTegers to FLOATs when dividing them.

    MONEY has no precision issue; that DECIMALs get to have a larger intermediate type used during calculations is just a 'feature' of using that type (and I'm not actually sure how far that 'feature' extends).

    To answer the specific question, a "compelling reason"? Well, if you want absolute maximum performance in a SUM(x) where x could be either DECIMAL or MONEY, then MONEY will have an edge.

    Also, don't forget it's smaller cousin, SMALLMONEY—just 4 bytes, but it does max out at 214,748.3647 - which is pretty small for money—and so is not often a good fit.

    To prove the point around using larger intermediate types, if you assign the intermediate explicitly to a variable, DECIMAL suffers the same problem:

    declare @a decimal(19,4)
    declare @b decimal(19,4)
    declare @c decimal(19,4)
    declare @d decimal(19,4)
    
    select @a = 100, @b = 339, @c = 10000
    
    set @d = @a/@b
    
    set @d = @d*@c
    
    select @d
    

    Produces 2950.0000 (okay, so at least DECIMAL rounded rather than MONEY truncated—same as an integer would.)

提交回复
热议问题