0

We have a table where we are using a column to store the price of the item. The column size is 17.2 decimal. We need to have both thousand separator and decimal separator in the string. We are currently using this:

SELECT '$' + convert(varchar,cast('2123232322323.21' as money),-1) as Price

But it raises an error if the size exceed 15 digits.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
Pankaj Saha
  • 869
  • 3
  • 17
  • 37

1 Answers1

1

The money type does not have sufficient range for the numbers that the OP is using. ideally this sort of thing would be done in the presentation layer but the OP wants a SQL solution so I've had a go at a TSQL solution. Someone with better TSQL than me can improve this but I believe it'll do what the OP wants. Ideally it'd be made into a more generic User Defined function. It doesn't take into account locales (some European countries use '.' as the thousand separator and ',' as the decimal point).

DECLARE @Price decimal(19,2)
DECLARE @PriceString varchar(20)
DECLARE @DP int
DECLARE @Decimals varchar(3)
DECLARE @ResultString varchar(25)

SELECT @Price = 12345678901234567.89
SELECT @PriceString = CONVERT(varchar(20), @Price)
SELECT @DP = CHARINDEX('.', @PriceString)
SELECT @Decimals = SUBSTRING(@PriceString, @DP, LEN(@PriceString)-@DP+1)
SELECT @PriceString = SUBSTRING(@PriceString, 1, @DP-1)
SELECT @PriceString = REVERSE(@PriceString)
DECLARE @ix int
SELECT @ResultString = ''
SELECT @ix = 1
WHILE @ix <= LEN(@PriceString)
BEGIN
    SELECT @ResultString = SUBSTRING(@PriceString, @ix, 1) + @ResultString
    if @ix %3 = 0 AND @ix <> LEN(@PriceString) 
    BEGIN
        SELECT @ResultString = ',' + @ResultString

    END
    SELECT @ix = @ix +1
END
SELECT @ResultString = @ResultString + @Decimals
SELECT @ResultString
OldBoyCoder
  • 876
  • 6
  • 16