Concatenate '$' with numeric value

▼魔方 西西 提交于 2019-12-24 09:52:57

问题


The SelectCommand for my GridView is as follows:

SELECT
  pubName AS Publication,
  COUNT(*) AS Total,
  SUM(CAST (price as INT)) AS Price 
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, -1, GETDATE())
GROUP BY pubName

Where I'm doing the SUM AS Price bit, I want to add a dollar sign ($) to the start, so my data displays as $109, instead of just 109. I tried just doing '$' + SUM, but of course that didn't work. Is there a way around this?


回答1:


Like in many languages, the plus sign is an overloaded operator in T-SQL - addition or string concatenation. When any of the types involved in the operation are numeric, precedence goes to addition. Of course you can't add strings and numbers in a meaningful way, so you get an error about conversion. In order to concatenate the values as strings, you must tell SQL Server that they're all strings. One way to do this is using CONVERT:

..., '$' + CONVERT(VARCHAR(12), SUM(CAST(price AS INT))) AS Price FROM ...

Note that in Denali you will be able to avoid the converts by using the new CONCAT function, which treats all types as strings and even treats NULL values as empty strings.



来源:https://stackoverflow.com/questions/7485423/concatenate-with-numeric-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!