About Me

My photo
Colorado
Paul has 18 years experience with Microsoft SQL Server. He has worked in the roles of production DBA, database developer, database architect, applications developer, business intelligence and data warehouse developer, and instructor for students aspiring for MCDBA certification. He has performed numerous data migrations and supported large databases (3 Terabyte, 1+ billion rows) with high transactions. He is a member of PASS, blogs about lessons learned from a developer’s approach to SQL Server administration, and has been the president of the Boulder SQL Server Users’ Group from January 2009 to present.

Wednesday, July 6, 2011

udfPadLeft()

This is a simple user-defined scalar function which will be referenced by subsequent posts.  It is just a tool that comes in very handy for formatting.


Use Admin
go

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/6/11            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







No comments:

Post a Comment