Click here to Skip to main content
15,884,298 members
Articles / Database Development / SQL Server / SQL Server 2008
Tip/Trick

SQL Server StringPadding (String function)

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
24 Apr 2013CPOL 18.9K   5   2
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)


Written By
Software Developer
United States United States
MCSD, MCTS, MCP
Personal Blog : http://www.codetoastdev.com/

Comments and Discussions

 
GeneralVery nice article Pin
gaurav23259-May-13 8:07
gaurav23259-May-13 8:07 
GeneralRe: Very nice article Pin
Surender Singh (CodeToastDev)10-May-13 7:16
Surender Singh (CodeToastDev)10-May-13 7:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.