Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2008

SQL Server StringPadding (String function)

24 Apr 2013CPOL 19.2K  
Custom StringPadding functions for SQL Server

Introduction

SQL Server 2008/2012 provides many string handling functions. You can find sub string, character or pattern index, left or right functions. Still you need to put some workaround if you need to pad a replicated character to the left or right side of a string. .NET and many other languages have built-in string padding functions.

Using the code

I created these function for String padding. 

  • StringPadLeft - Pads a string with leading characters to a specified total length.
  • StringPadRight - Pads a string with trailing characters to a specified total length.

Usage

SQL
Declare @CUSTOMER_ID as varchar(10)
Set @CUSTOMER_ID = dbo.StringPadLeft('46',10,'0')
Print @CUSTOMER_ID

StringPadLeft function

SQL
CREATE FUNCTION StringPadLeft 
 ( @String as Varchar(max),
   @Length as int,
   @Char as char(1)
 )
RETURNS Varchar(max)
AS
BEGIN

    Declare @PaddedString as Varchar(max)

    -- Return same string if @Length is smaller or equal to the length of @String value
    If(Len(@String) >= @Length )
            RETURN @String

    -- Create PaddedString
    Set @PaddedString = Replicate(@Char, @Length- Len(@String)) + @String

    -- Return the PaddedString
    RETURN @PaddedString

END

StringPadRight function

SQL
CREATE FUNCTION StringPadRight
 ( @String as Varchar(max),
   @Length as int,
   @Char as char(1)
 )
RETURNS Varchar(max)
AS
BEGIN

  Declare @PaddedString as Varchar(max)

    -- Return same string if @Length is smaller or equal to the length of @String value
    If(Len(@String) >= @Length )
            RETURN @String

    -- Create PaddedString
    Set @PaddedString = @String + Replicate(@Char, @Length- Len(@String))

    -- Return the PaddedString
    RETURN @PaddedString

END

Note : These functions will return same string if @Length is smaller or equal to the @String value.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)