Last active
May 29, 2019 16:26
-
-
Save morbidcamel101/e15f73b1426330a27f7faebf5bfc9a81 to your computer and use it in GitHub Desktop.
Generate a Code from a persons FullName in SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
C.[Name] | |
,C.Code + CAST(C.SEQ AS NVARCHAR(2)) AS Code | |
FROM | |
( | |
SELECT | |
O.* | |
,ROW_NUMBER() OVER(PARTITION BY dbo.udf_ExtractUpper([Name]) ORDER BY [Name] ASC) SEQ | |
FROM | |
(SELECT | |
DISTINCT | |
[Name] | |
,dbo.udf_ExtractUpper([Name]) Code | |
FROM | |
[Officers]) O | |
) C |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE FUNCTION [dbo].[udf_ExtractUpper] | |
( | |
@Val VARCHAR(200) | |
) | |
RETURNS NVARCHAR(200) | |
AS | |
BEGIN | |
--Return Val | |
DECLARE @RetCapWord VARCHAR(100) | |
SET @RetCapWord='' | |
;WITH CTE AS | |
( | |
SELECT @Val AS oldVal,1 AS TotalLen,SUBSTRING(@Val,1,1) As newVal, | |
ASCII(SUBSTRING(@Val,1,1)) As AsciVal | |
UNION ALL | |
Select oldVal,TotalLen+1 AS TotalLen, | |
SUBSTRING(@Val,TotalLen+1,1) AS newVal, | |
ASCII(SUBSTRING(@Val,TotalLen+1,1)) AS AsciVal | |
FROM CTE | |
WHERE CTE.TotalLen<=LEN(@Val) | |
) | |
SELECT @RetCapWord=@RetCapWord+newVal | |
FROM CTE | |
INNER JOIN master..spt_values as m on CTE.AsciVal=m.number and CTE.AsciVal between 65 and 90 | |
RETURN @RetCapWord | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment