从SQL Server中的指定字符串返回子字符串

时间:2016-02-17 10:18:15

标签: sql sql-server sql-server-2008 substring charindex

我在下面查询:

DECLARE @url varchar (max)='http://v.mercola.com/blogs/public_blog/New-Diet-Pill-Expands-1-000-Times-in-Your-Stomach-24728.aspx' 
SELECT replace(replace(RIGHT(@URL , CHARINDEX ('/' ,REVERSE(@URL))-1),'.aspx',''),'-',' ') as abc

返回低于输出:

实际输出 -

enter image description here

预期输出

enter image description here

,即我想在最后一次出现-之后消除字符串。

我必须做出哪些改变才能获得预期的输出 总之,我希望在/的最后一次出现之后以及-的最后一次出现之前有一个子串。如上所示。

请提前帮助和谢谢......!

3 个答案:

答案 0 :(得分:0)

这样的事情:

DECLARE @url varchar (max)='http://v.mercola.com/blogs/public_blog/New-Diet-Pill-Expands-1-000-Times-in-Your-Stomach-24728.aspx' 

declare @suffix varchar(max)
select @suffix = RIGHT(@URL , CHARINDEX ('/' ,REVERSE(@URL))-1)

select left(@suffix, len(@suffix) - charindex('-', reverse(@suffix)))

输出:

New-Diet-Pill-Expands-1-000-Times-in-Your-Stomach

答案 1 :(得分:0)

试试这个

DECLARE @url VARCHAR (max)='http://v.mercola.com/blogs/public_blog/New-Diet-Pill-Expands-1-000-Times-in-Your-Stomach-24728.aspx'

SELECT Reverse(LEFT(mid, Charindex('/', mid) - 1))
FROM   (SELECT Substring(Reverse(@url), Charindex('-', Reverse(@url)) + 1, Len(@url)) AS mid) a 

答案 2 :(得分:0)

另一种选择:

DECLARE @url varchar (max)='http://v.mercola.com/blogs/public_blog/New-Diet-Pill-Expands-1-000-Times-in-Your-Stomach-24728.aspx' 

DECLARE @LastSlash int = LEN(@URL) - CHARINDEX('/', REVERSE(@URL)) + 2,
        @LastMinus int = LEN(@URL) - CHARINDEX ('-', REVERSE(@URL)) + 1

SELECT SUBSTRING(@URL, @LastSlash, @LastMinus-@LastSlash)