Thursday, February 28, 2013

INITCAP Function in SQL Server




INITCAP Function in SQL Server



Create a user-defined function for SQL Server 2005:


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

1 comment:

  1. select stuff( lower(reverse(ParseName(replace(reverse(a),' ','.'),1))) , 1,1, left(upper(reverse(ParseName(replace(reverse(a),' ','.'),1))),1)) + ' ' +
    coalesce(stuff( lower(reverse(ParseName(replace(reverse(a),' ','.'),2))) , 1,1, left(upper(reverse(ParseName(replace(reverse(a),' ','.'),2))),1)), '') + ' ' +
    coalesce(stuff( lower(reverse(ParseName(replace(reverse(a),' ','.'),3))) , 1,1, left(upper(reverse(ParseName(replace(reverse(a),' ','.'),3))),1)),'') + ' ' +
    coalesce(stuff( lower(reverse(ParseName(replace(reverse(a),' ','.'),4))) , 1,1, left(upper(reverse(ParseName(replace(reverse(a),' ','.'),4))),1)), '')
    from (select 'GurJeEt sINGH KAmBoj ' a ) h

    ReplyDelete

web stats