Published on

February 3, 2015

Converting a String to Title Case in SQL Server

Recently, I received an interesting question via email about converting a string to title case in SQL Server. The sender was concerned whether such a question is appropriate for an interview. In this blog post, I will address this question and provide a solution to the problem.

Firstly, I believe that all questions are good questions in an interview. It’s not about the validity of the question itself, but rather the quality of the answer and the attitude of the candidate that determines their capability. If you encounter a question like this during an interview, it’s an opportunity to showcase your skills and problem-solving abilities.

Now, let’s dive into the solution. In my early career, I wrote a script to convert a string to title case, and I shared it in a previous blog post titled “SQL SERVER – UDF – Function to Convert Text String to Title Case – Proper Case”. I encourage you to read the comments on that post as they contain valuable information.

Here is the script from the blog post:

CREATE FUNCTION udf_TitleCase (@InputString VARCHAR(4000))
RETURNS VARCHAR(4000)
AS
BEGIN
    DECLARE @Index INT
    DECLARE @Char CHAR(1)
    DECLARE @OutputString VARCHAR(255)
    
    SET @OutputString = LOWER(@InputString)
    SET @Index = 2
    
    SET @OutputString = STUFF(@OutputString, 1, 1, UPPER(SUBSTRING(@InputString,1,1)))
    
    WHILE @Index <= LEN(@InputString)
    BEGIN
        SET @Char = SUBSTRING(@InputString, @Index, 1)
        
        IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
        IF @Index + 1 <= LEN(@InputString)
        BEGIN
            IF @Char != ''''
            OR UPPER(SUBSTRING(@InputString, @Index + 1, 1)) != 'S'
            SET @OutputString = STUFF(@OutputString, @Index + 1, 1, UPPER(SUBSTRING(@InputString, @Index + 1, 1)))
        END
        
        SET @Index = @Index + 1
    END
    
    RETURN ISNULL(@OutputString, '')
END

You can use this script as follows:

SELECT dbo.udf_TitleCase('This function will convert this string to title case!')

By executing the above query, you will get the following result:

This Function Will Convert This String To Title Case!

Now, you have a handy function to convert any string to title case in SQL Server. Feel free to use it in your projects or during interviews to demonstrate your SQL skills.

Remember, it’s not just about the answer, but also about your approach and attitude towards problem-solving. Good luck!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.