Question

I need some help with a sql transformation. This part of query that I have been provided with:

'$' + replace(cast((CAST(p.Price1 AS decimal(10,2)) * cast(isnull(p.Multiplier,1) as decimal(10,2))) as varchar), '.0000', '')

Basically, it ends up being a varchar that looks like this: $26980

I need to insert a comma at the thousand and million mark (if applicable). So in this instance, $26,980

What's the easiest way to do that without having to rewrite the whole thing?

Was it helpful?

Solution

Do it on the client side. Having said that, this example should show you the way.

with p(price1, multiplier) as (select 1234.5, 10)
select '$' + replace(cast((CAST(p.Price1 AS decimal(10,2)) * cast(isnull(p.Multiplier,1) as decimal(10,2))) as varchar), '.0000', ''),
       '$' + parsename(convert(varchar,cast(p.price1*isnull(p.Multiplier,1) as money),1),2)
from p

The key is in the last expression

'$' + parsename(convert(varchar,cast(p.price1*isnull(p.Multiplier,1) as money),1),2)

Note: if p.price1 is of a higher precision than decimal(10,2), then you may have to cast it in the expression as well to produce a faithful translation since the original CAST(p.Priced1 as decimal(10,2)) will be performing rounding.

OTHER TIPS

If you really must do it in TSQL you can use CONVERT(), but this sort of thing really doesn't belong in the database:

declare @m money = 12345678
-- with decimal places
select '$' + convert(varchar, @m, 1)
-- without decimal places
select '$' + replace(convert(varchar, @m, 1), '.00', '')

You could turn this into a function, it only goes 50 characters back.

DECLARE @input VARCHAR(50)
SELECT @input = '123123123.00'
SELECT @input = CASE WHEN CHARINDEX('.', @input) > offset +1
                      THEN STUFF(@input, CHARINDEX('.', @input) - offset, 0, ',') 
                      ELSE @input END
FROM (SELECT 3 offset UNION SELECT 7 UNION SELECT 12 UNION SELECT 18 UNION SELECT 25 UNION SELECT 33 UNION SELECT 42) b
PRINT @input

The offset grows by +1 for each position, because it's assuming you've already inserted the commas for the previous positions.

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