Writing an Oracle INITCAP Function in SQL Server

Hello everyone,

In this article, I will give information about writing the Oracle INITCAP function in SQL Server.

In SQL Server, in some cases, we may want to see and use functions that exist in other databases.

What is the INITCAP function?

While the INITCAP function converts the first character of the words in the text given as a parameter to uppercase, it also lowers the other characters.

You can easily do this with the help of the function below.

CREATE FUNCTION SQLServer_InitCap
(
    @InputString VARCHAR(4000)
)
RETURNS VARCHAR(4000)
AS
BEGIN

    DECLARE @Index INT;
    DECLARE @Char CHAR(1);
    DECLARE @PrevChar CHAR(1);
    DECLARE @OutputString VARCHAR(255);

    SET @OutputString = LOWER(@InputString);
    SET @Index = 1;

    WHILE @Index <= LEN(@InputString)
    BEGIN
        SET @Char = SUBSTRING(@InputString, @Index, 1);
        SET @PrevChar = CASE
                            WHEN @Index = 1 THEN
                                ' '
                            ELSE
                                SUBSTRING(@InputString, @Index - 1, 1)
                        END;

        IF @PrevChar IN ( ' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(' )
        BEGIN
            IF @PrevChar != ''''
               OR UPPER(@Char) != 'S'
                SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char));
        END;

        SET @Index = @Index + 1;
    END;

    RETURN @OutputString;

END;
GO

--Use of Function

SELECT dbo.SQLServer_InitCap('yavuz selim kart')

When you run the function, you will see a result like the one below.

Writing an Oracle INITCAP Function in SQL Server

As you can see, we have seen that the first character of the words in the text is capitalized.

Good luck to everyone in business and life.

22 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!