tags:

views:

73

answers:

2

I'm a novice so please excuse the simplicity of this. I am trying to get a total ammount, trim the excess decimal places than append some text.. it all works until I try ROUND it

ROUND(CAST(ServiceFee * COUNT(UserID) AS VARCHAR(20)),0) + CAST(' yen' as VARCHAR(20))

Thanks in advance

A: 

You have to round the value before you cast it:

CAST(ROUND(ServiceFee * COUNT(UserID),0) AS VARCHAR(20)) + ' yen'
Guffa
The + operator will attempt to *add* the numeric values of the two strings. The expression `'1' + ' yen'` returns just `1` in MySQL
intgr
@intgr: That depends on what database you use. In MSSQL it doesn't attempt to add the values as both are strings. As it works before the round() was called, the + operator is obviously not the issue.
Guffa
Fair enough. But SO doesn't let me cancel the downvote.
intgr
+1  A: 

Depends on the dialect of SQL.

For example, in MySQL the + operator is for mathematical addition only. If you want to concatenate the values, should use CONCAT() (in MySQL) or the || operator (other DBMSes that support standard SQL). You're also doing a redundant CAST within ROUND() because the ROUND function expects its argument to be numeric.

So here's the fixed statement in MySQL:

CONCAT(ROUND(ServiceFee * COUNT(UserID), 0), ' yen')

Or in standard SQL:

CAST(ROUND(ServiceFee * COUNT(UserID), 0) AS VARCHAR(20)) || ' yen'

(the CAST is probably redundant, but I kept it just in case you had a purpose for it)

intgr
The + operator concatenates strings just fine in MSSQL.
Guffa
That's why I asked user "Mark Hollas" which dialect of SQL he is talking about.
intgr