2

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

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.

4

3 回答 3

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

或更安全的方法(如果有没有空格分隔符的字符串):

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
于 2013-10-02T20:34:50.473 回答
0

CharIndex 返回 5,这是测试字符串中第一个空格的位置,位于“John”和“Doe”之间。

因此,Right 返回测试字符串最右边的 5 个字符,即“l.com”

于 2013-10-02T20:35:06.220 回答
0

嗨,你也可以试试rtrim

Declare @test varchar(50)
Select @test = 'John Doe johndoe@email.com'
SELECT RIGHT(@test, CHARINDEX(' ', REVERSE(rtrim(@test))))
于 2021-11-29T07:26:54.800 回答