在SQL中逐字排序

时间:2011-05-20 07:22:15

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

对于E.g

我有单词“John Roshan”我希望通过每个单词的第一个alphbet来安排这个顺序,这意味着上面单词的输出应该是“Roshan John”。

我想用SQL

来做

请帮我解决。

提前致谢

1 个答案:

答案 0 :(得分: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)')