80

请帮助我,如何使用函数过滤 SQL 中的单词?

我很难解释,所以我举个例子:

ID       |       WebsiteName      |
-----------------------------------
1        |      www.yahoo.com     |
2        |      www.google.com    |
3        |      www.youtube.com   |

我想要的是,如何获得网站的名称。我想选择具有这样输出的记录。如何删除“www。” 和记录中的“.com”。

ID      |      WebsiteName
--------------------------    
1       |        yahoo

谢谢您的帮助。:D

4

5 回答 5

132

这个怎么样?

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @Input

    SET @Work = REPLACE(@Work, 'www.', '')
    SET @Work = REPLACE(@Work, '.com', '')

    RETURN @work
END

然后使用:

SELECT ID, dbo.StripWWWandCom (WebsiteName)
FROM dbo.YourTable .....

当然,这是受到严格限制的,因为它只会www.在开头和.com结尾剥离 - 仅此而已(因此它不适用于其他主机名称,例如,等smtp.yahoo.com其他 Internet 域).org.edu.de

于 2013-01-27T18:16:51.343 回答
13

This one get everything between the "." characters. Please note this won't work for more complex URLs like "www.somesite.co.uk" Ideally the function would check for how many instances of the "." character and choose the substring accordingly.

CREATE FUNCTION dbo.GetURL (@URL VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @URL

    SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, LEN(@work))   
    SET @Work = SUBSTRING(@work, 0, CHARINDEX('.', @work))

    --Alternate:
    --SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, CHARINDEX('.', @work) + 1)   

    RETURN @work
END
于 2013-01-28T16:19:47.700 回答
9

我可以给一个小hack,你可以使用T-SQL函数。试试这个:

SELECT ID, PARSENAME(WebsiteName, 2)
FROM dbo.YourTable .....
于 2013-01-27T18:28:49.053 回答
5

You can use stuff in place of replace for avoiding the bug that Hamlet Hakobyan has mentioned

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250)) 
RETURNS VARCHAR(250) 
AS BEGIN
   DECLARE @Work VARCHAR(250)
   SET @Work = @Input

   --SET @Work = REPLACE(@Work, 'www.', '')
   SET @Work = Stuff(@Work,1,4, '')
   SET @Work = REPLACE(@Work, '.com', '')

   RETURN @work 
END
于 2015-01-06T21:19:06.677 回答
1

This will work for most of the website names :

SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....

于 2018-12-17T11:01:17.947 回答