Click here to monitor SSC
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Charpad - Character Padding Function

By Richard Doering,

Introduction :

This is a function to align fixed character strings to a fixed size.output

Usage :

The function has 4 mandatory parameters, defined as follows >

@Input - the string to be formatted

@OutputWidth - the desired width of the output string

@OutputAlign - either 'LEFT' or 'RIGHT' , depending on where you want the input string aligned.

@PadCharacter - the character to perform the padding with.

Behaviour :

The function returns a string of length specified in @OutputWidth containing the text in @Input aligned by @OutputAlign using @PadCharacter to perform the alignment.

I use '*' in this example rather than a space for easier display here >

SELECT dbo.CharPad ('Excelsis Dei',20,'RIGHT','*')

********Excelsis Dei

SELECT dbo.CharPad ('731',7,'RIGHT','0')



If the length of the input string is greater than the width specified for the output, the output will still be aligned as requested, but will be truncated to the requested width,
I felt this behaviour was more desirable than a NULL result.

SELECT dbo.CharPad ('Small Potatoes',5,'LEFT',' ')


SELECT dbo.CharPad ('The Erlenmeyer Flask',5,'RIGHT',' ')



Finally, if you accidently specify the exact length of your input string, you get the same string back regardless of alignment.

SELECT dbo.CharPad ('Nothing Important Happened Today',14,'RIGHT',' ')

Nothing Important Happened Today


I wrote this to format systems reports into tables before sending them by email. Thought I'd share it with the community.



Richard Doering

Total article views: 2003 | Views in the last 30 days: 4
Related Articles

How to right-align a text column - SQL Srv 2000

How to right-align a text column - SQL Srv 2000


right aligned data

hi, my query is: SELECT CAST(OID AS varchar(15)) ........................... this is a possible r...


UDF to return a multi column table of values from an input string

This UDF returns a multi column table of values from an input string of comma separated values


Aligned and non-aligned Partition Indexex

Aligned and non-aligned Partition Indexes

string manipulation