Tuesday, 1 April 2008

SQL - Capitalise function

This function will capitalise the first letter of every word in a sentence. The commented line can be used to ignore single letter words.

create function dbo.Capitalise
(
@Text varchar( 1000 )
)

returns varchar( 1000 )

as

begin
declare @ReturnString varchar( 1000 )
set @ReturnString = ''

declare @Word varchar(30)

declare @Pointer int
set @Pointer = 0

if right( @Text, 1 ) <> ' '
set @Text = @Text + ' '

while charindex( ' ', @Text, @Pointer ) > 1
begin
set @Word = substring( @Text, @Pointer, charindex( ' ', @Text, @Pointer ) - @Pointer )

--if len( @Word ) > 1
set @Word = upper( left( @Word, 1 ) ) + lower( right( @Word, len( @Word ) - 1 ) )

set @Pointer = charindex( ' ', @Text, @Pointer ) + 1
set @ReturnString = @ReturnString + @Word + ' '
end

set @ReturnString = rtrim( ltrim( @ReturnString ) )

return @ReturnString
end

Example:
select dbo.Capitalise( 'this is a test' ) as CapitalisedSentence

2 comments:

Jeff said...

wonderful! thank you!

Anonymous said...

Thanks for this nice article, it's absolutely famous blogs