Here is my solution, and it has these features / features:
- It can handle, however, many names per line. (That is, less than two or more than three.)
- All spaces between names are retained.
I know that the OP indicated that in his case there can only be 2 or 3 names. I'm not against. I just use a solution that works, and if it is not suitable for a specific problem, this is normal.
So here is the function:
CREATE FUNCTION dbo.fnGetInitials (@name varchar(max)) RETURNS varchar(max) AS BEGIN DECLARE @cutpos int, @spacepos int, @result varchar(max); DECLARE @cutlist TABLE (CutPos int, SpacePos int); SET @result = LTRIM(RTRIM(@name)); SET @cutpos = 2; SET @spacepos = CHARINDEX(' ', @result); WHILE @spacepos > 0 BEGIN INSERT INTO @cutlist VALUES (@cutpos, @spacepos); SET @spacepos = @spacepos + 1; SET @cutpos = @spacepos + 1; SET @spacepos = CHARINDEX(' ', @result, @spacepos); END; DELETE FROM @cutlist WHERE CutPos >= SpacePos; SELECT @result = STUFF(@result, CutPos, SpacePos - CutPos, '') FROM @cutlist ORDER BY CutPos DESC; RETURN @result; END;
And here is the test call:
SELECT dbo.fnGetInitials(' John Ronald Reuel Tolkien ');
and the result:
source share