2011-05-20 35 views
0

對於E.g爲了用字SQL

我有一句話「約翰·羅斯漢」我想安排由每個單詞的第一個alphbet這個順序,這意味着上述字的輸出應該是「羅山約翰」。

我想與SQL

做到這一點請大家幫幫我的urget。

在此先感謝

+3

目前還不清楚你問什麼。 'J'在'R'之前。 – 2011-05-20 07:28:24

+0

你的意思是你有一列存儲名字作爲名字,姓氏,但你想輸出它作爲姓氏,名字? – 2011-05-20 07:33:40

+1

我討厭問,但是...應該John2排序還是John10之後? :-) – 2011-05-20 07:39:21

回答

2
declare @S varchar(50) 
set @S = 'John Roshan 2000' 

;with cte as 
(
    select 
    1 as P1, 
    charindex(' ', @S+' ', 1) as P2 
    union all 
    select 
    C.P2+1, 
    charindex(' ', @S+' ', C.P2+1) as P2 
    from cte as C 
    where charindex(' ', @S+' ', C.P2+1) > 0 
) 

select 
(
    select substring(@S, P1, P2-P1)+' ' 
    from cte 
    order by substring(@S, P1, P2-P1) 
    for xml path(''), type 
).value('.', 'varchar(50)') 
+1

+1,因爲這很可能是OP的含義。 – 2011-05-20 08:34:05