Monday, April 26, 2010

Get the first character in each word using Sql Server

A user-defined function to get the first character from each and every word.

The below function will get the string as input and will give each and every character in starting of the words.
This function will be very much useful when you try to get the short-form for
designation, and also it will be helpful in getting the acronym for a set of
words.

CREATE FUNCTION dbo.getShortForm
(
@InputString VARCHAR(100)
)
RETURNS VARCHAR(100)
/*
Created by Alwyn Duraisingh.M on 23rd April 2010 12:30 PM
before leaving to office (heaven) :-)
Purpose: To get each and every word
*/
AS
BEGIN

DECLARE @GetFirstChar VARCHAR(50),@Index INT
, @stringLength INT, @Flag INT
SET @Flag = 0
SET @Index = 1
SET @stringLength = LEN(@InputString)
-- self defence
IF((@InputString is not NULL) AND (@InputString <> ''))
BEGIN
SET @GetFirstChar = UPPER(LEFT(@InputString,1))
--looping out each and every character
WHILE(@Index <= @stringLength) BEGIN IF (@Flag = 1) BEGIN IF(SUBSTRING(@InputString,@Index,1) <> ' ')
BEGIN
SET @GetFirstChar = @GetFirstChar + UPPER(SUBSTRING(@InputString,@Index,1))
END
END
IF(SUBSTRING(@InputString,@Index,1) = ' ')
BEGIN
SET @Flag = 1
END
ELSE
BEGIN
SET @Flag = 0
END
SET @Index = @Index + 1
END
END
RETURN @GetFirstChar
END


You can execute the function like

SELECT dbo.getShortForm('Senior Analyst')

OutPut
******
SA

No comments:

Post a Comment