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

  • Is sql injection possible in stored procedures with text param?
  • Arithmetic overflow on column sum in sql server
  • What makes a SQL statement sargable?
  • Can't create a database in SQL Server 2012
  • How do you get full error information for a stored procedure error out of LINQ-to-SQL or SQL Server?
  • UUID madness with mssql
  • 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.

  • Split a string to only use the middle part in SQL
  • Using CHARINDEX and SUBSTRING in a CASE statement
  • SQL Charindex vs LIKE operator
  • How to get string between two characters
  • Using Charindex with in Substring is resulting in error
  • Find string in column value SQL 2008?
  • 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'
            WHEN CHARINDEX(' ', REVERSE(@test)) > 0 THEN RIGHT(@test, CHARINDEX(' ', REVERSE(@test))-1)
            ELSE @test

    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.