Friday, February 4, 2011

Right Align text 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.

  • 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)
    
    Euro Micelli : Bravo! How did I miss this? Do note that STR() takes a float, not a decimal. SQLServer Help is very explicit about it ("... an expression of approximate numeric (float) data type"): if your decimals have enough digits, rounding will cause you trouble. This is still a great answer for most
    From 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
    
    From Espo
  • The easiest way is to pad left:

    CREATE FUNCTION PadLeft(@PadString nvarchar(100), @PadLength int)
    RETURNS nvarchar(200)
    AS
    begin
    return  replicate(' ',@padlength-len(@PadString)) + @PadString
    end
    go
    print dbo.PadLeft('123.456', 20)
    print dbo.PadLeft('1.23', 20)
    
    From Josef

0 comments:

Post a Comment