简体   繁体   English

SQL新列与模式匹配

[英]SQL new column with pattern match

I have a column with a url sting that looks like this 我有一栏显示网址字符串,看起来像这样

http://www.somedomain.edu/rootsite1/something/something/ or http://www.somedomain.edu/sites/rootsite2/something/something http://www.somedomain.edu/rootsite1/something/something/http://www.somedomain.edu/sites/rootsite2/something/something

Basically I want to ONLY return the string up to root site (in another column).. root site can be anyting (but /sites), but it will either follow /sites/ or .edu/ 基本上我只想将字符串返回到根站点(在另一列中)..根站点可以是任意位置(但/ sites),但是它将跟随/ sites /或.edu /

so the above two strings would return: 因此以上两个字符串将返回:

http://www.somedomain.edu/rootsite1
http://www.somedomain.edu/sites/rootsite2

I can't compile the view with CLR, so I don't think Regex is an option. 我无法使用CLR编译视图,因此我不认为Regex是一个选择。

Thanks for any help. 谢谢你的帮助。

I think you'll do better by splitting up the URL on the client side and saving it as two pieces in the table (one containing the "root" site, the other containing the site-specific path), then putting them back together again on the client side after retrieval. 我认为您可以通过在客户端上拆分URL并将其保存为表中的两个部分(一个包含“根”站点,另一个包含站点特定路径),然后将它们重新放在一起来做得更好在客户端检索之后。

If you choose to store them in the table as you describe above, you can use CHARINDEX to determine where the .edu or /sites/ occurs in the string, then use SUBSTRING to break it up based on that index. 如果选择如上所述将它们存储在表中,则可以使用CHARINDEX来确定.edu/sites/在字符串中的位置,然后使用SUBSTRING根据该索引对其进行分解。

If you really need to do this, here's an example: 如果您确实需要这样做,请参考以下示例:

declare @sites table (URL varchar(500))

insert into @sites
values
('http://www.somedomain.edu/rootsite1/something/something/'),
('http://www.somedomain.edu/sites/rootsite2/something/something')

select
    URL,
    SUBSTRING(URL, 1, case when charindex('/sites/', URL) > 0 then 
        charindex('/', URL, charindex('/sites/', URL) + 7) else 
        charindex('/', URL, charindex('.edu/', URL) + 5) end - 1)

from @sites

you could use CHARINDEX, LEN and SUBSTRING to do this although im not sure sql is the best place to do it 您可以使用CHARINDEX,LEN和SUBSTRING来执行此操作,尽管我不确定sql是执行此操作的最佳位置

DECLARE @testStr VARCHAR(255)
SET @testStr = 'http://www.somedomain.edu/rootsite1/something/something/'

PRINT SUBSTRING(@testStr, 0, CHARINDEX('.edu', @testStr))

Not a full solution but should give you a start 不是完整的解决方案,但应该给您一个开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM