I am looking get few letters in a string of words. So it should be first 5 characters (if there are more than 5 if not then the whole word and the subsequent first characters of the next words 5+1(+1...)
E.g. Key Account Sales I would like to get just "KeyAS" or HR General - HRG
I am currently using this
ALTER FUNCTION [dbo].[fnFirsties5]
(
@str NVARCHAR(4000)
)
RETURNS NVARCHAR(2000)
AS
BEGIN
DECLARE retval NVARCHAR(2000);
SET str=RTRIM(LTRIM(@str));
SET retval=LEFT(@str,5);
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 –
but this gives a result as "Key AAS" or "HR GeG"
Few more things to note
Version - Microsoft SQL Server 2008 R2 (SP3-GDR) (KB4057113) - 10.50.6560.0 (X64) Dec 28 2017 15:03:48 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.0 (Build 6002: Service Pack 2) (Hypervisor)
Currently what I get
Empl ID Name Job Family Description
123 John Smith Key AAS Key Account Sales
124 karen Smith HR GeG HR General
213 John Doe Production Operator Production Operator
What I expect
Empl ID Name Job Family Description
123 John Smith Key AS Key Account Sales
124 karen Smith HR G HR General
213 John Doe ProduO Production Operator
Code that I am currently using is
ALTER FUNCTION [dbo].[fnFirsties5] ( @str NVARCHAR(4000) )
RETURNS NVARCHAR(2000)
AS
BEGIN
DECLARE @retval NVARCHAR(2000);
SET @str=RTRIM(LTRIM(@str));
SET @retval=LEFT(@str,5);
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
Thanks