August 21, 2013 at 9:24 am
How to format varchar to currency. Negative amounts to ($100.50) with parentheses?
August 21, 2013 at 10:16 am
Could you post DDL, sample data and expected results to give us a clearer idea of what you want?
Check the article linked on my signature to find out how. No need for lots of data or real data, just what should be necessary to give a good perspective.
August 21, 2013 at 10:19 am
DECLARE @var varchar(10), @money money
SET @var = ($111.11)
SET @money = -1* CAST(CASE WHEN LEFT(@var,1) <> '(' THEN @var
ELSE SUBSTRING(@var, 2, LEN(@var) - 1)
END AS money)
PRINT @money
SET @var = $222.22
SET @money = CAST(CASE WHEN LEFT(@var,1) <> '(' THEN @var
ELSE SUBSTRING(@var, 2, LEN(@var) - 1)
END AS money)
PRINT @money
NOTE: this code does NOT guarantee that your varchar is castable as a money, and it WILL blowup if it is not!! It will also blow up if the trailing ')' is not there.
P.S. Once again I get to say that CASE is my favorite 4-letter TSQL word!! 😎
Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service
August 21, 2013 at 11:07 am
Basically, I'm trying to convert a column that has a negative amount to be placed inside parentheses. So far I've been playing with the following: SELECT TransactionDate, Cast(Replace(Replace(TransactionValue,'-', '($'), '',')') as varchar) AS TransactionValue
FROM tblTransactionImport
So far the output looks like this:
($9306.78
($1.44
($1.05
($288.63
($300.53
($353.4
37.7
I need the missing ')' for negative amounts and the '$' for positive amounts. Maybe the CASE will work for the positive amounts.
Thank you.
August 21, 2013 at 12:04 pm
CRAP!! I went backwards!! Just a sec and I will have a fix ...
Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service
August 21, 2013 at 12:08 pm
CASE WHEN @money < 0 THEN '(' + CAST(@money AS varchar(20)) + ')' ELSE CAST(@money AS varchar(20)) END
Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service
Viewing 6 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply