Adds

Saturday 20 September 2014

How to Title Case a Column Value Using SQL Query

Create a scalar-valued functions in database,

CREATE FUNCTION dbo.fn_title_case
(
  @str AS varchar(100)
)
RETURNS varchar(100)
AS
BEGIN

  DECLARE
    @ret_str AS varchar(100),
    @pos AS int,
    @len AS int

  SELECT
    @ret_str = ' ' + LOWER(@str),
    @pos = 1,
    @len = LEN(@str) + 1

  WHILE @pos > 0 AND @pos < @len
  BEGIN
    SET @ret_str = STUFF(@ret_str,
                         @pos + 1,
                         1,
                         UPPER(SUBSTRING(@ret_str,@pos + 1, 1)))
    SET @pos = CHARINDEX(' ', @ret_str, @pos + 1)
  END

  RETURN RIGHT(@ret_str, @len - 1)


END

======

Execute this update sql query

UPDATE dbo.Client
  SET ClientName = dbo. fn_title_case(ClientName)