How can I get the negative sign to the right of the number when using CAST to varchar?

Converting a numeric to varchar, using cast...  but, it's putting the negative sign to the left.

How can I get it to put it on the right?

Also, how can I right adjust the field?

August 30th, 2013 5:01pm

By violating the first principle of C/S and any tiered architecture. All display formatting is done in the presentation layers, never, never  in the database. This is SQL, not COBOL! You do not even know that fields are not columns. 
Free Windows Admin Tool Kit Click here and download it now
August 30th, 2013 5:41pm

Can you provide an example for the input and expecte
August 30th, 2013 5:52pm

As Celko noted, it's much easier to do this in the front end in a language meant to do formatting.  To do it in SQL you need to convert the number to a string and then use the character manipulations to get the result into the format you desire.  For example,

Declare @Test Table (MyData int);
Insert @Test(MyData) Values (7456), (-23456), (0);
Select Right('      ' + Cast(Abs(MyData) As varchar(11)), 6) 
    + Case When MyData < 0 Then '-' Else '' End As Result 
From @Test;
Tom

Free Windows Admin Tool Kit Click here and download it now
August 30th, 2013 6:10pm

There is no standard formatting mask in SQL, so you'll have to create this specific format yourself. My first choice would be to do this in the application that uses the data. If it must be done in the database, you could use something like this:

SELECT CAST(ABS( my_numeric ) AS varchar(39))
       + CASE WHEN my_numeric < 0 THEN '-' ELSE '' END
           AS formatted_numeric
FROM my_table

I'm not sure what you mean with "adjust the field".

September 1st, 2013 4:00am

There is no standard formatting mask in SQL, so you'll have to create this specific format yourself. My first choice would be to do this in the application that uses the data. If it must be done in the database, you could use something like this:

SELECT CAST(ABS( my_numeric ) AS varchar(39))
       + CASE WHEN my_numeric < 0 THEN '-' ELSE '' END
           AS formatted_numeric
FROM my_table

I'm not sure what you mean with "adjust the field".

Free Windows Admin Tool Kit Click here and download it now
September 1st, 2013 4:00am

You can place the - sign at the end using the FORMAT function in SQL Server 2012:

Declare @Test Table (MyData int);
Insert @Test(MyData) Values (7456), (-23456), (0), (-342), (-2333444),(1000000);
Select FORMAT(MyData, '###,###,###;###,###,###-')  From @Test;
/*
7,456
23,456-

342-
2,333,444-
1,000,000
*/

SQL Server 2012 new features:

http://www.sqlusa.com/sql-server-2012-new-features/

September 1st, 2013 6:21am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics