Search code examples
c#sql-server-2005substringpatindex

SQL Server 2005 Query SUBSTRING & PATINDEX


i have in my database three word phrases:

for example: "JKH Drainage Units"

Does anyone knows how to get the first letter of the third word?

i need to extract the "U" of the "Units" word.

N.B. i tried to use SUBSTRING(Phrase, PATINDEX('% % %', Phrase) + 1, 1) but it didn't work for me...


Solution

  • I've broken it down step-by-step, just to show the method to my madness:

    declare @Phrase varchar(100)
    set @Phrase = 'JKH Drainage Units'
    
    /* The first space */
    select charindex(' ', @Phrase, 1)
    
    /* The second space */
    select charindex(' ', @Phrase, charindex(' ', @Phrase, 1) + 1)
    
    /* The first character after the second space */
    select substring(@Phrase, charindex(' ', @Phrase, charindex(' ', @Phrase, 1) + 1)+1, 1)