Click here to Skip to main content
15,885,961 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
I've an Item table like;

Item Name        Price       Currency      CurrencySymbol
---------        -----       --------      --------------
ItemA             500          USD              $
ItemB             100          EURO             €
ItemC             150          USD              $

....

so what i need is , returning price data with correct currency formating.
Suppose i executed a query , it shall return dataset as ;

ItemName       TotalPrice
--------       ----------
ItemA             $ 500
ItemB             100 €
ItemC             $ 150


so how can i do it with SQL/TSQL ?
Posted
Comments
Mehdi Gholam 23-Nov-11 11:01am    
It's better not to do this as it will mangle your sorting.

Don't do this in SQL, it's not the job of the database to format data. Instead, format the data in whatever medium you are presenting this information.

If you're presenting the information in a web app, you could apply the formatting at that stage.

It's the job of the presenter to format the data in the way it should be viewed, not the database


If you really insist on doing it in the database, some horrible mangled CASE statement would probably work :)

SQL
SELECT 
    ItemName, CASE WHEN Currency = 'EURO' THEN CONVERT(VARCHAR(10), Price) + CurrencySymbol ELSE CurrencySymbol + CONVERT(VARCHAR(10), Price) END AS FormattedPrice 
FROM
    ItemsTable
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-Nov-11 11:23am    
Reasonable. It could be done on the road to presenting the data. In the case DataGridView is used, OP can have a column which is not data bound and not used for sorting (see the comment to the question by Mehdi).
My 5.
--SA
Amir Mahfoozi 23-Nov-11 11:26am    
+5
thatraja 23-Nov-11 11:35am    
That's right, 5!
[no name] 23-Nov-11 13:04pm    
My current solution is formatting data at application side.I thought it would be better to fetch formatted data from database.I understand that now, it is a bad idea.
Thanks,
Hi....


Check this Example...


SQL
DECLARE @Item TABLE (ItemName VARCHAR(30), Price NUMERIC(12,2), Currency VARCHAR(10), CurrencySymbol NVARCHAR(1))

INSERT INTO @Item (ItemName,Price,Currency,CurrencySymbol)
SELECT 'ItemA',500,'USD','$'
UNION ALL 
SELECT 'ItemB',100,'EURO','€'
UNION ALL
SELECT 'ItemC',150,'USD','$'

SELECT ItemName,CurrencySymbol + CAST(Price AS NVARCHAR) 'TotalPrice' FROM @Item
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900