解析sql表中的名字和姓氏

时间:2017-01-30 21:16:10

标签: sql sql-server sql-server-2008 parsing

我的SQL Server 2008数据库中有一个包含c/o Full Name的列。我遇到了将名字和姓氏分开的问题。我在自己的专栏中有c / o,但我需要名字/姓氏。我知道第二和第三个案例陈述存在问题,但我不确定我需要改变什么。我应该在某处存储索引变量来引用它们吗?

Declare @t table ( [name] varchar(100) )

INSERT INTO @t ( Name )
SELECT Street1 FROM tblPeople
WHERE CO = 'Y' AND LastName NOT LIKE 'SUMMERHAVEN INC' AND Street1 Like '%c/o%'

SELECT
    [name],
    CHARINDEX(' ', [name]),
    CASE WHEN CHARINDEX(' ', [name]) > 0 THEN
        LEFT([name],CHARINDEX(' ',[name])-1)
    ELSE
        [name]
    END as CO,
    CASE WHEN CHARINDEX(' ', [name]) > 0 THEN
        SUBSTRING([name],CHARINDEX(' ',[name])+1, ( LEN([name]) - CHARINDEX(' ',[name])+1) )
    ELSE
        NULL
    END as FIRST_NAME,
    CASE WHEN CHARINDEX(' ', [name]) > 0 THEN
        SUBSTRING([name],CHARINDEX(' ',[name])+1, ( LEN([name]) - CHARINDEX(' ',[name])+1) )
    ELSE
        NULL
    END as LAST_NAME
FROM @t

3 个答案:

答案 0 :(得分:2)

令我惊讶的是,PARSENAME()于2008年推出

考虑以下

Declare @YourTable table (Name varchar(50))
Insert Into @YourTable values 
 ('c/o Cher')
,('c/o John Smith')
,('John Smith')

Select *
      ,FirstName=parsename(replace(ltrim(rtrim(replace(name,'c/o',''))),' ','.'),2)
      ,LastName =parsename(replace(ltrim(rtrim(replace(name,'c/o',''))),' ','.'),1)
 From @YourTable

返回

Name            FirstName   LastName
c/o Cher        NULL        Cher
c/o John Smith  John        Smith
John Smith      John        Smith

答案 1 :(得分:1)

披露:解析这样的数据是一个坏主意,但是你去了:

Declare @t table ( [name] varchar(100) )

insert into @t ( Name ) values ('c/o Full Name')

SELECT
CASE WHEN CHARINDEX(' ', [name]) > 0 THEN
    LEFT([name],CHARINDEX(' ',[name])-1)
ELSE
    [name]
END as CO,
CASE WHEN CHARINDEX(' ', [name]) > 0 THEN
    SUBSTRING([name],CHARINDEX(' ',[name])+1, CHARINDEX(' ',[name]) )
ELSE
    NULL
END as FIRST_NAME,
CASE WHEN CHARINDEX(' ', [name]) > 0 THEN
    SUBSTRING([name],CHARINDEX(' ',[name], CHARINDEX(' ',[name])+1), len([name]))
ELSE
    NULL
END as LAST_NAME
FROM @t

答案 2 :(得分:1)

这是一种使用公用表表达式的方法,这样找到要打破的空间的逻辑就是合理的自我记录。

Declare @t table ( [name] varchar(100) )

insert into @t ( Name )
select 'one two three'
union select 'a bc def'
union select 'one two'
union select 'one'

;with cte1 as 
(
    select name
    ,charindex(' ', name) FirstSpace
    from @t
)
, cte2 as (
    select name
    , FirstSpace
    ,charindex(' ', name, FirstSpace+1) SecondSpace
    from cte1
)
select name
, FirstSpace
, SecondSpace
, case when FirstSpace=0 then name else substring(name, 1, FirstSpace-1) end Company
, case when SecondSpace=0 then null else substring(name, FirstSpace+1, SecondSpace-FirstSpace-1) end FirstName
, case when SecondSpace=0 or SecondSpace=len(name) then null else substring(name, SecondSpace+1, len(name)-SecondSpace) end LastName
from cte2