SQL Function to make all TEXT to propercase in SQL Server

There are times when you want to change the text from the table to a proper case in SQL Server and here’s a small resuable function that lets you do it.

SQL Function to make all TEXT to propercase in SQL Server

create function ConvertToTitleCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
  declare @Reset bit;
  declare @Ret varchar(8000);
  declare @index int;
  declare @c char(1);

  if @Text is null
    return null;

  select @Reset = 1, @index = 1, @Ret = '';

  while (@index <= len(@Text))
    select @c = substring(@Text, @index, 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,
      @index = @index + 1
  return @Ret
end

You can call the function as shown below.

declare @input varchar(8000) = 'this is a developerpublish.com portal'

select [dbo].[ConvertToTitleCase](@input)

You should see the output as shown below

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this blog post, let’s learn about the error message “1459 – An error occurred while accessing the database mirroring...
In this blog post, let’s learn about the error message “7937 – Columnstore index has one or more missing column...