Search code examples
sql-servert-sqlvarchar

Most efficient: Cut off varchar after first space?


What is the most efficient way to cut off a varchar after the first space i.e. given 'FIRST_STRING SECOND_STRING THIRD_STRING', it should return 'FIRST_STRING'? This will be run on potentially 100s of thousands of rows.


Solution

  • Notice the +' ' this will trap any single word

    Example

    Declare @S varchar(max) = 'FIRST_STRING SECOND_STRING THIRD_STRING'
    
    Select left(@S,charindex(' ',@S+' ')-1)
    

    Returns

    FIRST_STRING