Remove trailing spaces and zero from a string in SQL-Server

In this blog, I will discuss about “How to remove trailing spaces and zeros from a string without using any trim function”.
I have written a procedure for the same. In one of my blog where I have shared the code for removing the leading zeros and spaces, here as well, code is almost the same.

CREATE PROCEDURE [dbo].[RmTrailingZerosSpcs] (@String VARCHAR(500) )
as
BEGIN
DECLARE @output VARCHAR(100) = '';
DECLARE @prev CHAR(1) = '';
DECLARE @c CHAR(1) = '';
DECLARE @i int = 1;
DECLARE @len int;
DECLARE @len_zeros int =0;
declare @reversestring varchar(200)
select @reversestring= reverse(@String)
SET @len = len(@reversestring);
WHILE(@i <= @len)
begin SET @c = SUBSTRING(@reversestring, @i, 1);
IF @c='0' or @c=' '
BEGIN
SET @len_zeros=len(@c)+@i
SET @output = substring(@reversestring,@len_zeros, @len);
SET @i = @i + 1;
END ;
IF @c<>'0' and @c!=' '
BEGIN
SET @i = @i + 1;
break;
END
END
select reverse(@output)
END


Here, everything is same except reverse function which is used to reverse the string and then apply same logic.

Related posts