I have an external app passing strings in camelcase. Users are looking to report on the string and want it formatted as a sentence. The string may have words in it with all caps that I need to add spaces around.
built out a function based on this question here: Is there any SQL Server built-in function to convert string in camel case? however, it does not work with the all caps words. Below is my modified version.
DECLARE @String NVARCHAR(MAX) = 'ThisIsASentenceWithCAPTIInIt'
--, @Len INT -- = LEN(@String)
, @Delimiter CHAR(1) = ' '
, @Iterator INT = 2; --Don't put space to left of first even if it's a capital
WHILE @Iterator <= LEN(@String)
-- Iterate through string
BEGIN
-- Check if current character is Uppercase (lowercase = 0)
IF PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator, 1) COLLATE Latin1_General_CS_AI) <> 0
-- Do this if capital
BEGIN
-- check if the previous character is lowercase, if it is then add a space before the current character.
IF(
(PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator - 1, 1) COLLATE Latin1_General_CS_AI) = 0
AND SUBSTRING(@String, @Iterator - 1, 1) <> ' '
)
OR PATINDEX('[ABCDEFGHIJKLMNOPQRSTUVWXYZ]', SUBSTRING(@String, @Iterator + 1, 1) COLLATE Latin1_General_CS_AI) = 0)
BEGIN
SET @String = STUFF(@String, @Iterator, 0, @Delimiter);
SET @Iterator+=1;
END;
-- check if the next character is lowercase, if it is then add a space before the current character.
SET @Iterator+=1;
END;
---- Don't care about current character being lowercase. Just continue iterating
SET @Iterator+=1;
END;
SELECT @String;
Example of what I get from the app - "ThisIsASentenceWithCAPTIInIt"
What I want to pass back - "This Is A Sentence With CAPTI In It"
What I am getting back from my modified version - "This Is ASentence With CAPTIIn It"