quarta-feira, 5 de agosto de 2015

Capitalize the first letter of each word in a String

Ever need to pretify data in a column putting the first letter of each word in UPPERCASE?

How about using this function:

CREATE FUNCTION [dbo].[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 

You can find the original here: http://www.sql-server-helper.com/functions/initcap.aspx

Check out my new book about R Language http://www.amazon.com/dp/B00SX6WA06

Nenhum comentário:

Postar um comentário

Leave your comment here!