Tuesday, July 23, 2013

udfPadLeft()

This object is referenced by various other objects in this blog.

USE Admin
IF OBJECT_ID('dbo.udfPadLeft') Is Not Null
      DROP FUNCTION dbo.udfPadLeft
GO

CREATE FUNCTION dbo.udfPadLeft(
      @In varchar(100),
      @Width int,
      @PadChar varchar(1)
      )
RETURNS varchar(100)
AS
/*    DATE        AUTHOR            REMARKS
      7/23/13           PPaiva            Initial creation.
     
      DESCRIPTION
            Pads @In with @PadChar so that the length of the returned
            value is @Width.  If the length of @In is greater than @Width
            then @In is returned. 

      USAGE
            SELECT dbo.udfPadLeft('7', '3', '0')

*/
BEGIN
      DECLARE @Out varchar(100),
                  @LenIn int


      SET @LenIn = Len(@In)
     
      IF @Width - @LenIn < 0
            SET @Out = @In
      ELSE
            SET @Out = REPLICATE(@PadChar, @Width - @LenIn) + @In

      RETURN @Out

END