SQL Server Ltrim或substring仅用于获取电子邮件地址

时间:2013-10-04 20:09:45

标签: sql-server substring

我有这种情况:

John Doe johndoe@email.com
John johndoe@email.com

我想离开那只会解析如下:

John Doe
John

换句话说,只删除电子邮件地址。

我试过这个:

SELECT
                (CASE WHEN CHARINDEX(‘ ‘, REVERSE(column1)) > 0 THEN Left(column1, CHARINDEX(‘ ‘, REVERSE(column1)) – 1)
                ELSE column1
                END) AS column1
FROM Book1

3 个答案:

答案 0 :(得分:1)

你走在正确的轨道上...只需添加len功能并删除“减1”

SELECT  (CASE WHEN CHARINDEX(' ', REVERSE(column1)) > 0 THEN Left(column1, len (column1) - CHARINDEX(' ', REVERSE(column1)))
                ELSE column1
                END) AS column1
FROM Book1

答案 1 :(得分:1)

DECLARE @MyTable TABLE
(
    ID      INT IDENTITY(1,1) PRIMARY KEY,
    Col1    NVARCHAR(200) NOT NULL
);
INSERT  @MyTable(Col1) VALUES(N'John Doe johndoe@email.com');
INSERT  @MyTable(Col1) VALUES(N'John johndoe@email.com');
INSERT  @MyTable(Col1) VALUES(N'johndoe@email.com');
INSERT  @MyTable(Col1) VALUES(N' johndoe@email.com');

SELECT  *,
    CASE 
        WHEN oa.SpaceIndex > 0 THEN RIGHT(t.Col1, oa.SpaceIndex - 1)
        ELSE t.Col1
    END AS EmailAddress,
    CASE 
        WHEN oa.SpaceIndex > 0 THEN LEFT(t.Col1, LEN(t.Col1) - oa.SpaceIndex)
        -- or WHEN oa.SpaceIndex > 0 THEN NULLIF( LEFT(t.Col1, LEN(t.Col1) - oa.SpaceIndex), '' )
    END AS FullName 
FROM    @MyTable t
OUTER APPLY( SELECT CHARINDEX(N' ', REVERSE(t.Col1) ) AS SpaceIndex) oa

结果:

ID Col1                       SpaceIndex EmailAddress      FullName
-- -------------------------- ---------- ----------------- --------
1  John Doe johndoe@email.com 18         johndoe@email.com John Doe
2  John johndoe@email.com     18         johndoe@email.com John
3  johndoe@email.com          0          johndoe@email.com NULL
4   johndoe@email.com         18         johndoe@email.com 

答案 2 :(得分:0)

DECLARE @Str VARCHAR(MAX) = 'John Doe johndoe@email.com'


 SELECT LEFT(@Str, LEN(@Str) - LEN(REVERSE(SUBSTRING(REVERSE(@Str), 1, CHARINDEX(' ', REVERSE(@Str)) - 1))))