Getting first letter of the string with SQL Script

Often times developers need to come up with the alphabet for a very long list of values, so that list can be broken into chunks and then each of those chunks can be retrieved based on the first letter or firts symbol of the text. 

While you can do it easily with C# or VB, you may implement in your database. This will be more efficient, since all the work that you need to do is dedicated to normally powerfull backend server and you can reuse this code across multiple database project via converting it into functions.


declare @string varchar(8000)

set @string = ‘my words to get first letter from’


declare @Wordstable(word varchar(1000))

declare @LenString int


while len( @string ) > 0



select @LenString = (case charindex( ' ', @string )

when 0 then len( @string )

else ( charindex( ' ', @string ) -1 )



insert into @Words

select substring( @string, 1, @LenString )


select @string = (case ( len( @string ) - @LenString )

when 0 then ''

else right( @string, len( @string ) - @LenString - 1 )





declare @WordsResults varchar(8000)

set @WordsResults = ''

select @WordsResults = @WordsResults + left(word,1)

from @Words


select @WordsResults