使用通配符仅选择字符串的一部分(SQL Server)

时间:2018-10-11 23:50:21

标签: sql-server tsql

我正在尝试仅使用通配符选择URL字符串的一部分。

示例:

https://www.google.com.au/search?rlz=1C1GGRV_enAU787AU788&ei=9N6_W5o5w-b4BrKTvsgE&q=stackoverflow&oq=stackoverflow&gs_l=psy-ab.3..0i131i67k1j0l4j0i10k1j0l4.427511.429162.0.429260.13.8.0.0.0.0.314.525.2-1j1.2.0....0...1.1.64.psy-ab..11.2.524....0.NEXVTCFK4GA

通配符为%//%/%

我只想选择%// /%(粗体部分)。对于任何给定格式相同的URL,都需要这样做。

如何使用子字符串,替换,charindex来做到这一点?

还是有其他替代方法?

1 个答案:

答案 0 :(得分:1)

解决方案:

DECLARE @urls TABLE (urlId INT IDENTITY, urlText VARCHAR(500) NOT NULL);
INSERT @urls(urlText)
VALUES
('https://www.amazon.com/SQL-Server-MVP-Deep-Dives/dp/1617290475'),
('http://sqlblog.com/blogs/rob_farley/archive/2011/11/08/when-is-a-sql-function-not-a-function.aspx'),
('http://sqlblogcasts.com/blogs/simons/archive/2015/04/26/non-parallelizable-operations-in-sql-server.aspx'),
('http://www.sqlinthewild.co.za/index.php/2009/04/29/functions-io-statistics-and-the-execution-plan/'),
('https://www.brentozar.com/archive/2014/10/sql-server-functions-dragging-query/');

SELECT urlId   = u.urlId, 
       urlText = u.urlText, 
       [url]   = SUBSTRING(u.urlText,front.pos,txt.ln)
FROM @urls AS u
CROSS APPLY (VALUES(CHARINDEX('//',u.urlText)+2)) AS front(pos)
CROSS APPLY (VALUES(CHARINDEX('/',u.urlText,front.pos)-front.pos)) AS txt(ln);

结果:

urlId   urlText                                                 url
------- ------------------------------------------------------- ---------------------
1       https://www.amazon.com/SQL-Server-MVP-Deep-Dives/dp...  www.amazon.com
2       http://sqlblog.com/blogs/rob_farley/archive/2011/11...  sqlblog.com
3       http://sqlblogcasts.com/blogs/simons/archive/2015/0...  sqlblogcasts.com
4       http://www.sqlinthewild.co.za/index.php/2009/04/29/...  www.sqlinthewild.co.za
5       https://www.brentozar.com/archive/2014/10/sql-serve...  www.brentozar.com
相关问题