Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first letter of each word in a SQL string [duplicate]

Possible Duplicate:
sql to pick apart a string of a persons name and output the initials

In MS-SQL Server, there is a way to get the first letter of each word in a string? For example:

Name:

Michael Joseph Jackson

Query:

SELECT name, [function] as initial FROM Customers

Result:

MJJ

like image 866
Aldonas Avatar asked Feb 15 '12 20:02

Aldonas


People also ask

How do you extract first 5 letter of a string in SQL?

The LEFT() function extracts a number of characters from a string (starting from left).

How do I get the first occurrence of a string in SQL?

Searching from the start of a string expression. This example returns the first location of the string is in string This is a string , starting from position 1 (the first character) of This is a string . SELECT CHARINDEX('is', 'This is a string'); Here is the result set.

How do I make the first letter of each word capital in SQL Server?

SQL UPPER Function. We use SQL UPPER function to convert the characters in the expression into uppercase. It converts all characters into capital letters.

How do I get the first letter of each word in SQL?

Use the INITCAP() function to convert a string to a new string that capitalizes the first letter of every word. All other letters will be lowercase.


1 Answers

This function will shield your results against multiple sequential spaces in the source string:

CREATE FUNCTION dbo.fnFirsties ( @str NVARCHAR(4000) )
RETURNS NVARCHAR(2000)
AS
BEGIN
    DECLARE @retval NVARCHAR(2000);

    SET @str=RTRIM(LTRIM(@str));
    SET @retval=LEFT(@str,1);

    WHILE CHARINDEX(' ',@str,1)>0 BEGIN
        SET @str=LTRIM(RIGHT(@str,LEN(@str)-CHARINDEX(' ',@str,1)));
        SET @retval+=LEFT(@str,1);
    END

    RETURN @retval;
END
GO

SELECT dbo.fnFirsties('Michael Joseph Jackson');
SELECT dbo.fnFirsties('  Michael   Joseph Jackson  '); -- multiple space protection :)

Results:

MJJ
MJJ
like image 141
John Dewey Avatar answered Oct 07 '22 09:10

John Dewey