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?
Technology Tips and News
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?
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
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".
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".
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/