Saturday, July 19, 2008

Function to Trim any Character/String from Left of varchar in SQL Server

An Extended Left Trim (LTRIM) Function for SQL Server which removes given string/character from Left of another varchar (String)

Level: Intermediate

Knowledge Required:
  • T-SQL
  • SQL Server 2005
  • SQL Server User Define Functions
Description:
The SQL Server's built-in LTrim() function removes only the blanks (spaces) from Left of a varchar (string). Here is a User Defined function which can remove any character.

CREATE FUNCTION [dbo].[LTrimString]
(
-- Add the parameters for the function here
@StringToTrim varchar(max),
@CharToTrim varchar(10)
)
RETURNS varchar(max)
AS
BEGIN

-- Declare the return variable here
DECLARE @Result varchar(max);
DECLARE @i int;
DECLARE @l int;
DECLARE @sl int;

SET @i = 1;
SET @l = Len(@StringToTrim);
SET @sl = Len(@CharToTrim);
While @i < @l
Begin
If
SubString(@StringToTrim, @i, @sl) <> @CharToTrim
Begin
SET @Result = SubString(@StringToTrim, @i, @l - @i + 1);
Break;
End
SET
@i = @i + @sl;
End

SET
@Result = IsNull(@Result, @StringToTrim);

-- Return the result of the function
RETURN @Result;
END

Usage:
Print dbo.LTrimString('00000005221', '0')

Output:
5221

No comments: