Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right Align Numeric Data in SQL Server

We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...

I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:

Value
----------
   143.55
  3532.13
     1.75

How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".

I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.

Thank you.

like image 588
Euro Micelli Avatar asked Sep 11 '08 15:09

Euro Micelli


2 Answers

The STR function has an optional length argument as well as a number-of-decimals one.

SELECT STR(123.45, 6, 1)

------
 123.5

(1 row(s) affected)
like image 115
d91-jal Avatar answered Oct 09 '22 22:10

d91-jal


If you MUST do this in SQL you can use the folowing code (This code assumes that you have no numerics that are bigger than 40 chars):

SELECT REPLICATE(' ', 40 - LEN(CAST(numColumn as varchar(40)))) + 
CAST(numColumn AS varchar(40)) FROM YourTable
like image 33
Espo Avatar answered Oct 09 '22 21:10

Espo