Trim Leading Characters using SQL functions

The code sample is a snippet that trims the leading characters in the input string.

For example, if the input is " hi " (please ignore quotes), and we choose to remove leading spaces, the output will be "hi ".

Trimming, generally, is a popular string manipulation function that helps remove unnecessary leading and trailing characters. This function removes the leading spaces alone.



CREATE FUNCTION [dbo].[fn_Trim_leading_characters] ( @Input VARCHAR(50), @LeadingCharacter CHAR(1) )
RETURNS VARCHAR(50)
AS
BEGIN
RETURN REPLACE(LTRIM(REPLACE(@Input, ISNULL(@LeadingCharacter, '0'), ' ')),
' ', ISNULL(@LeadingCharacter, '0'))
END
GO



One other example could be to remove leading 'a' characters from "aabc", the output now is "bc".


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: