SQL Server rtrim ltrim and charindex

我的未来我决定 提交于 2019-12-12 19:24:46

问题


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.


回答1:


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



回答2:


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"



来源:https://stackoverflow.com/questions/19146268/sql-server-rtrim-ltrim-and-charindex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!