Queens Dev
Some more ASP.NET

SQL Server Function - Remove Leading Characters

June 29, 2008 at 6:48 AM by bjsetegn

Here is a simple piece of code that will remove a specified character from the beginning of a string.  I don't know who the orginal author of this function is, I believe it has been around for quite awhile.  I made some changes to it so that if the first character is a minus sign '-' then it will trim leading characters around that minus sign.  This was to take care of changing '-0.57' to '-.57'.  There could be some extra logic thrown in there to trim around a user defined variable and not just '-' and to turn the feature on and off.  I didn't need it so I'll leave that up to somebody else.

This function works by replacing the character we want to trim with a space ' ' and then calling LTRIM on the string.  This will remove all spaces on the left and then the remaing spaces are replaced with the defined character.  NOTE: Because this replaces all spaces with the defined character this function should only be used on string without spaces in them.

Code 

/* ---------------------------------------------------------------------------------

PURPOSE

    The purpose of this function is to remove all leading characters from a string.

    This will also trim leading zeros around a minus sign

    Ex. Trim '0.57%' down to '.57%'

    Ex. Trim '-0.57%' down to '-.57%'

    Ex. Trim 'CCFFDDCCEE' remove C down to 'FFDDCCEE'

 

select dbo.ufn_TrimLeadingCharacters('-0001235005500', '0')

*/----------------------------------------------------------------------------------

 

ALTER FUNCTION dbo.ufn_TrimLeadingCharacters ( @Input VARCHAR(50), @LeadingCharacter CHAR(1) )

 

    RETURNS VARCHAR(50)

 

AS

BEGIN

 

Declare @returnValue as Varchar(50)

 

If SUBSTRING(@Input, 1, 1) = '-'

Begin

    Set @returnValue = Right(@Input, Len(@Input) - 1 )

    Set @returnValue = REPLACE(LTRIM(REPLACE(@returnValue, ISNULL(@LeadingCharacter, '0'), ' ')),

                   ' ', ISNULL(@LeadingCharacter, '0'))

    Set @returnValue = '-' + @returnValue

End

 

Else

Begin

    Set @returnValue = REPLACE(LTRIM(REPLACE(@Input, ISNULL(@LeadingCharacter, '0'), ' ')),

                   ' ', ISNULL(@LeadingCharacter, '0'))

END

 

 

RETURN @returnValue

 

End

Comments

February 26. 2010 01:31

instant personal loans

Derive happiness in oneself from a good day's work, from illuminating the fog that surrounds us.

instant personal loans

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading