.NET Programming With Me

SQL Server: Change the text to Title Case

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Description: Change the text to Title Case
-- Referenced : http://joezack.com/2008/10/20/mysql-capitalize-function/
-- =============================================
CREATE FUNCTION CAP_FIRST 
(
@myText VARCHAR(255)
)
RETURNS VARCHAR(255)
AS
BEGIN
DECLARE @len INT;
    DECLARE @i INT;

    SET @len   = LEN(@myText);
    SET @myText = LOWER(@myText);
    SET @i = 0;

    WHILE (@i < @len)
BEGIN
IF (SUBSTRING(@myText,@i,1) = ' ' OR @i = 0) 
BEGIN
            IF (@i < @len) 
                SET @myText = LEFT(@myText,@i) + '' + UPPER(SUBsTrING(@myText,@i + 1,1)) + '' + RIGHT(@myText,@len - @i - 1);
END
        SET @i = @i + 1;
    END;

    RETURN @myText;

END
GO



USAGE:
SeleCT dbo.CAP_FIRST(emp_name) as [Name]


No comments: