--Purpose: Eliminate blank spaces (up to three words)
--Author: Artemakis Artemiou
--Input Parameter: Varchar(250)
--Output: Varchar(250)
--
CREATE FUNCTION [dbo].[NoBlankSpaces]
(
@string varchar(250)
)
RETURNS varchar(250)
AS
BEGIN
declare @part1 as varchar(100)
declare @part2 as varchar(100)
declare @part3 as varchar(100)
declare @part4 as varchar(100)
declare @temp as varchar(100)
set @part1=(rtrim(substring(@string,0,(charindex(' ',ltrim(@string))))))
set @temp=ltrim(substring(@string,(charindex(' ',@string)),len(@string)+1))
set @part2=SUBSTRING(@temp,0,CHARINDEX(' ',@temp))
set @temp=SUBSTRING(@temp,0,250)
set @part3=ltrim(SUBSTRING(@temp,CHARINDEX(' ',@temp),250))
set @string=rtrim(ltrim(@part1+' '+@part2+' '+@part3))
RETURN @string
END
GO
-------------End of Function DDL-----------------
As you can see in the above DDL code, I am using a combination of the SUBSTRING, LTRIM, RTRIM and the CHARINDEX SQL Server built-in string functions for achieving my goal.
Now, let's use the function and see what the outcome will be: