在TSQL中交换字符串

时间:2016-08-01 11:07:28

标签: sql tsql

在T-SQL中,如何交换2个子串?

我的网址栏目有:

https://www.host.com/test/last-first

如何将其更改为:

https://www.host.com/test/first-last

例如:

https://www.host.com/test/smith-tim --> https://www.host.com/test/tim-smith

这甚至可能吗?

2 个答案:

答案 0 :(得分:0)

我认为https://www.host.com/test字符串对所有记录都相同。

https://www.host.com/test的长度为27

DECLARE @Value NVARCHAR(MAX) = 'https://www.host.com/test/smith-tim'

SELECT 
    SUBSTRING(@Value, 27, CHARINDEX('-', @Value, 27)) AS FullName, -- smith-tim
    SUBSTRING(@Value, 27, CHARINDEX('-', @Value, 27) - 27) AS FirstName, -- smith
    SUBSTRING(@Value, CHARINDEX('-', @Value, 27) + 1, 10000) AS LastName, -- tim
    SUBSTRING(@Value, 0, 27) + 
        SUBSTRING(@Value, CHARINDEX('-', @Value, 27) + 1, 10000) + '-' +
        SUBSTRING(@Value, 27, CHARINDEX('-', @Value, 27) - 27) AS Result -- https://www.host.com/test/tim-smith

答案 1 :(得分:0)

这没有长度限制,总是拾取最后一个字符...

这也可以优化并用作标量udf ..

declare @string varchar(max)
set @string='https://www.host.com/test/last-first'



;with 
cte
as
(select *,row_number() over (order by (select null)) as rownum,@string as string
 from 
[dbo].[SplitStrings_Numbers](@string,'/')
)
,cte1
as
(select string,b.item,rn,c.item as itemtobereplaced
from cte c  
cross apply
(
select * ,row_number() over (order by (select null)) as rn
from [dbo].[SplitStrings_Numbers](c.item,'-')
) b
where rownum=5
)
select distinct 
replace(string,itemtobereplaced,finalstringtobreplaced) as finalstring
from cte1 t1
cross apply
(select '-'+item from cte1 t2  where t1.string=t2.string order by rn desc for xml path(''))  b( newvalue)
cross apply
(select stuff(b.newvalue,1,1,'')) a2(finalstringtobreplaced)

输出

https://www.host.com/test/first-last