Technical Article

Left pad any string with another char

,

Pads a string (e.g. a number that needs left padding with zeros) with any character for as many as it takes to bring the inputted string to the total desired length. 

/****** Object:  User Defined Function dbo.fn_PadLeft    Script Date: 4/30/2002 1:29:16 PM ******/  
CREATE  FUNCTION fn_PadLeft (@MyString  Varchar(255),   
                  @PadChar  char(1), @TotLen  Int)  
  
-- Pads a string (typically a number, with zeros) with any character for a  
-- given Character for as many as it takes to bring the inputted string to  
-- the length in TotLen  
-- Input:  MyString -- the string being padded  
--         PadChar -- the character that will be the "padding"  
--         TotLen  -- the total length you want the resulting output to be  
-- Output: a padded string  
-- Note: This only pads on the LEFT side of a string  
-- Greg Milner,    Sep 2001  
  
  
RETURNS Varchar (255)  
  
AS      
  
BEGIN  
    IF @TotLen > Len(RTrim(LTrim(@MyString)))   
            
        DECLARE @PADDED Varchar(255)      
        SET @PADDED = REPLICATE(@PadChar,@TotLen-LEN(Ltrim(Rtrim(@MyString)))) + @MyString  
           
    RETURN @PADDED      
END

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating