Wednesday, 7 April 2010

Character Padding Function

This is a function I've written to align fixed character strings to a fixed size.output.It has been published on SQLServerCentral.com  today.

SSC : Character Padding Function

March 2011 Update : Putting the function here too now as SSC exclusivity period over...
/*
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

No comments: