Question

After reading most articles, my understanding is that if we multiple number fields against MONEY, it should return Money.

This works fine if my field is INT.

ISNULL(POFTotal.Total * [Price],0) AS [Total Purchases PO ($)]

In above POF.Total is INT and Price is money. And it returns result as Currency(Decimal) in my .Net app. But for below, where NFFTotal.Total is float, it returns result as float or double in my .Net app.

ISNULL(NFFTotal.Total * [Price],0) AS [Total NY COGS ($)]

I can convert it as below code, but like to understand why the difference between INT and FLOAT here.

CONVERT(money,ISNULL(NFFTotal.Total * [Price],0)) AS [Total NY COGS ($)]
Was it helpful?

Solution

In quite a few languages1, you're not actually allowed to mix data types that you supply to an operator. What happens is such languages is that they will define data type precedence rules, and use those rules to determine the "best" type in which to perform a calculation. It will then convert types of a lower precedence into the higher precedence type, and then perform the calculation.

And so, if we look at the precedence rules for SQL Server, we see the float is of a higher precedence than money, which in turn is of a higher precedence than int. So that's why when you mix int and money in an expression, you get a result of type money, and why when you mix float and money in an expression, you get float.

After reading most articles, my understanding is that if we multiple number fields against MONEY, it should return Money.

Well, I don't know which articles you read, but I'd say they're unreliable at best.


1This answer started by saying "most languages" but then I realised that it was quite a dated comment. In modern languages, especially ones that allow custom operators and for operators to be overloaded, it's not necessarily the case. But no-one would ever accuse T-SQL of being a modern language.

OTHER TIPS

MONEY and INT are fixed-point datatype, while FLOAT is float-point datatype.

    money      -922,337,203,685,477.5808 to 922,337,203,685,477.5807  8 bytes
    smallmoney -214,748.3648 to 214,748.3647                          4 bytes

so if you use

    NFFTotal.Total * [Price]

the result is float type and you need CONVERT to make it work with MONEY.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top