Technical Article

Charpad - Character Padding Function

,

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')

0000731

 

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',' ')

Small

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

Flask

 

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.

r

 

Richard Doering

http://sqlsolace.blogspot.com

/*
Script  : Character Padding Function
Version : 1.0 (April 2010)
Author  : Richard Doering
Web     : http://sqlsolace.blogspot.com
*/CREATE FUNCTION dbo.CharPad (
 @Input VARCHAR(255)
,@OutputWidth INT
,@OutputAlign VARCHAR(5)
,@PadCharacter CHAR(1) )
RETURNS VARCHAR(255)
AS
BEGIN
DECLARE @Output VARCHAR(255)
DECLARE @InputWidth INT

SET @InputWidth = LEN(@Input)

IF @InputWidth > @OutputWidth
BEGIN 
IF @OutputAlign = 'LEFT'
BEGIN
SET @Output = LEFT(@Input,@OutputWidth)
END
IF @OutputAlign = 'RIGHT'
BEGIN
SET @Output = RIGHT(@Input,@OutputWidth)
END
END

IF @InputWidth < @OutputWidth 
BEGIN 
IF @OutputAlign = 'RIGHT'
BEGIN
SET @Output = REPLICATE(@PadCharacter, @OutputWidth - @InputWidth ) + @Input
END
IF @OutputAlign = 'LEFT'
BEGIN
SET @Output =@Input+ REPLICATE(@PadCharacter, @OutputWidth - @InputWidth )
END
END

IF @InputWidth = @OutputWidth 
SET @Output = @Input


RETURN (@Output)
END

GO

Rate

4.36 (11)

You rated this post out of 5. Change rating

Share

Share

Rate

4.36 (11)

You rated this post out of 5. Change rating