SQL Server rtrim ltrim and charindex

I have the following scenario
John Doe johndoe@email.com
john johndoe@email.com

I want away that I can detect the first right space and just exclude everything to the left so I just get the email address of the person. So:
John Doe johndoe@email.com should be johndoe@email.com
john johndoe@email.com should be johndoe@email.com

  • How do I create a temporary table for a dynamic query so that I can BCP the output
  • sql server 2000 TSQL: creating index on table variable
  • Fastest way to insert data into an Sql Server Database using C#.net
  • TSQL query to find un-used stored procedures
  • Convert 2 datatable to one table
  • Sql Sever 2008 Select and Delete deadlock on the same index
  • This is what i have

    Declare @test varchar(50)
    Select @test = 'John Doe johndoe@email.com'
    SELECT Right(@test, CHARINDEX(' ', @test))
    

    This is only giving me the email.com!

    Thank you.

  • Splitting a dynamic string
  • Find string in column value SQL 2008?
  • SQL Server substring with optional character
  • Split a string to only use the middle part in SQL
  • Filter a specific word in SQL Server by row number
  • SQL query for parsing a body of text to extract a string from a list
  • 2 Solutions collect form web for “SQL Server rtrim ltrim and charindex”

    Declare @test varchar(50)
    Select @test = 'John Doe johndoe@email.com'
    SELECT RIGHT(@test, CHARINDEX(' ', REVERSE(@test)-1))
    

    or a safer approach (if there are strings without space separator):

    Declare @test varchar(50)
    Select @test = 'johndoe@email.com'
    SELECT 
        CASE 
            WHEN CHARINDEX(' ', REVERSE(@test)) > 0 THEN RIGHT(@test, CHARINDEX(' ', REVERSE(@test))-1)
            ELSE @test
        END
    

    CharIndex is returning 5, which is the position of the first space in your test string, between “John” and “Doe”.

    Right is therefore returning the right-most 5 characters of your test string, which are “l.com”

    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.