如何拆分和逗号分隔的名称?

时间:2014-06-26 17:11:49

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

我有这个专栏

NAME
John Stephenson
James Martin
Anna Corelia

如何选择此列?

NAME
Stephenson, John
Martin, James
Corelia, Anna 

5 个答案:

答案 0 :(得分:1)

您的问题与TRIM()功能无关。您可能正在尝试使用LEFT()的{​​{1}}和RIGHT()函数并使用SQL Server

连接它们来获得类似下面的内容
,

将导致

select right('John Stephenson',(len('John Stephenson')-charindex(' ','John Stephenson')))
+ ', ' + left('John Stephenson',(charindex(' ','John Stephenson') - 1))

答案 1 :(得分:1)

单程

;with test(name) as (
    select 'John Stephenson' union all
    select 'James Martin' union all
    select 'Anna J. Corelia' union all
    select 'BOBBYTABLES'
)
select
case when charindex(' ', name) = 0 then name  
else right(name, charindex(' ', reverse(name)) - 1) + ', ' + substring(name, 1, len(name) - charindex(' ', reverse(name))) end
from test


(No column name)
Stephenson, John
Martin, James
Corelia, Anna J.
BOBBYTABLES

答案 2 :(得分:0)

这是一个解决方案,包括我如何获得最终输出列。

这将处理三个部分名称,例如" Rip Van Winkle",也没有空格的名称,并将从名称中删除(修剪)任何前导/尾随空格。

DECLARE @NAMES TABLE (NAME NVARCHAR(MAX))
INSERT INTO @NAMES (NAME) VALUES ('John Stephenson'),('James Martin'),('Anna Corelia'),('Rip Van Winkle'),('Sally')

SELECT *, 
       CHARINDEX(' ',LTRIM(RTRIM(NAME))) [SpaceLocation],
       CASE WHEN CHARINDEX(' ',LTRIM(RTRIM(NAME)))>0 THEN RIGHT(LTRIM(RTRIM(NAME)), LEN(LTRIM(RTRIM(NAME)))-CHARINDEX(' ',LTRIM(RTRIM(NAME)))) END [LastName],
       CASE WHEN CHARINDEX(' ',LTRIM(RTRIM(NAME)))>0 THEN LEFT(LTRIM(RTRIM(NAME)),CHARINDEX(' ',LTRIM(RTRIM(LTRIM(RTRIM(NAME)))))-1) END [FirstName],
       CASE WHEN CHARINDEX(' ',LTRIM(RTRIM(NAME)))>0 THEN RIGHT(LTRIM(RTRIM(NAME)), LEN(LTRIM(RTRIM(NAME)))-CHARINDEX(' ',LTRIM(RTRIM(NAME)))) + ', ' +LEFT(LTRIM(RTRIM(NAME)),CHARINDEX(' ',LTRIM(RTRIM(NAME)))-1) ELSE LTRIM(RTRIM(NAME)) END [FinalOutput]
FROM @NAMES

答案 3 :(得分:0)

SELECT substring(NAME+', '+NAME,charindex(' ',NAME)+1,len(NAME)+1) FROM MyTable

这也会将"Rip Van Winkle"变为"Van Winkle, Rip"

<强> SQL Fiddle Demo

答案 4 :(得分:-1)

没有单一的修剪功能,但你可以

 select   ltrim(rtrim(colname)) from tablename 

将TRIM双方。

但你需要的是:

declare @name varchar(300) ='Stephenson John';
Select  

Substring(@name, 1,Charindex(' ', @name)-1) +
', '  +
Substring(@name, Charindex(' ', @name)+1, LEN(@name))
 as name

抱歉,我想念帖子