Function for trimming spaces in a given string expression

-- function for trimming spaces in a given string expression.
if object_id('dbo.svnTrimUnusedSpaces') is not null
drop function dbo.svnTrimUnusedSpaces
go

create function svnTrimUnusedSpaces(@StringExpr nvarchar(max))
returns nvarchar(max)
as
begin

-- check for null condition
set @StringExpr = isnull(@StringExpr, '')

-- check for empty strings
if len(@StringExpr) > 1
begin

set @StringExpr = ltrim(rtrim( @StringExpr ))

-- Trim spaces here
while (charindex(' ', @StringExpr ) > 1)
begin
set @StringExpr = replace(@StringExpr, ' ', '')
end

end

return @StringExpr
end
go



-- sample inputs
select dbo.svnTrimUnusedSpaces('hello world')
select dbo.svnTrimUnusedSpaces('hello world ')
select dbo.svnTrimUnusedSpaces(' hello world ')
select dbo.svnTrimUnusedSpaces(null)

Comments

Popular Posts