What is wrong with this function... The function intends to remove the specified leading characters from a given string. I know there is a patindex base solution to this which however doesn't consider spaces and all zero entries... but I want to know what is wrong with this one...
If I input "00012345" it should out put me "12345" however the output I'm getting is "0001234".. Why?
The test data is:
DECLARE @result varchar(max)
EXEC @result = TrimLeadingChar '00012345'
PRINT @result
The function code is:
CREATE FUNCTION TrimLeadingChar
(
@st AS Varchar(max),
@trimChar AS Varchar(1) = "0"
)
RETURNS Varchar(max)
AS
BEGIN
DECLARE @index int
DECLARE @temp Varchar(1)
SET @index = 0
if LEN(RTRIM(LTRIM(@st))) <= 1
return @st;
While(@index < LEN(@st))
BEGIN
set @temp = substring(@st,@index,1)
if @temp = @trimChar
SET @index = @index + 1
else
Break;
END
Return substring(@st,@index, LEN(@st))
END
GO