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
The LEFT() function extracts a number of characters from a string (starting from left).
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.
SQL UPPER Function. We use SQL UPPER function to convert the characters in the expression into uppercase. It converts all characters into capital letters.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With