MSSQL - Make Proper Case
- Home
- SQL Server
- MSSQL - Make Proper Case
This function:
- "Proper Cases" all "UPPER CASE" words that are delimited by white space
- leaves "lower case words" alone
- works properly even for non-English alphabets
- is portable in that it does not use fancy features of recent SQL server versions
- can be easily changed to use NCHAR and NVARCHAR for unicode support,as well as any parameter length you see fit
- white space definition can be configured an H2 tag with other complimentary information on one line?
CREATE FUNCTION ToProperCase(@string VARCHAR(255)) RETURNS VARCHAR(255)
AS
BEGIN
DECLARE @i INT
DECLARE @l INT
DECLARE @c NCHAR(1)
DECLARE @f INT
DECLARE @o VARCHAR(255)
DECLARE @w VARCHAR(10)
SET @w = '[' + CHAR(13) + CHAR(10) + CHAR(9) + CHAR(160) + ' ' + ']'
SET @i = 1
SET @l = LEN(@string)
SET @f = 1
SET @o = ''
WHILE @i <= @l
BEGIN
SET @c = SUBSTRING(@string, @i, 1)
IF @f = 1
BEGIN
SET @o = @o + @c
SET @f = 0
END
ELSE
BEGIN
SET @o = @o + LOWER(@c)
END
IF @c LIKE @w SET @f = 1
SET @i = @i + 1
END
RETURN @o
END
Result
dbo.ToProperCase('ALL UPPER CASE and SOME lower ÄÄ ÖÖ ÜÜ ÉÉ ØØ ĈĈ ÆÆ')
All Upper Case and Some lower Ää Öö Üü Éé Øø Cc Ææ
Here is a UDF that will also work:
create function ProperCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
declare @Reset bit;
declare @Ret varchar(8000);
declare @i int;
declare @c char(1);
if @Text is null
return null;
select @Reset = 1, @i = 1, @Ret = '';
while (@i <= len(@Text))
select @c = substring(@Text, @i, 1),
@Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,
@Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
@i = @i + 1
return @Ret
end
SQL MSSQL ProperCase function UDF