计算链接数SQL

时间:2014-02-27 15:34:32

标签: sql sql-server

我有一个包含一列原始电子邮件文本的表,包括标题和邮件正文。这可能包含也可能不包含我的域名的网址。如果它确实包含来自我的域的URL,我想在结果中添加一行并增加该URL的出现次数。

例如,结果应如下所示:

Link    Count 
----    -----
a       19
b       5
c       1

对此有何明智之处?

1 个答案:

答案 0 :(得分:0)

我在SQLMag(Brian Moran)上找到了一个可能有用的函数: 请注意我没有测试过这个功能,所以你可能想自己做这个:)

CREATE function WordRepeatedNumTimes
(@SourceString varchar(8000),@TargetWord varchar(8000))
RETURNS int
AS
BEGIN
DECLARE @NumTimesRepeated int
    ,@CurrentStringPosition int
    ,@LengthOfString int
    ,@PatternStartsAtPosition int
    ,@LengthOfTargetWord int
    ,@NewSourceString varchar(8000)

SET @LengthOfTargetWord = len(@TargetWord)
SET @LengthOfString = len(@SourceString)
SET @NumTimesRepeated = 0
SET @CurrentStringPosition = 0
SET @PatternStartsAtPosition = 0
SET @NewSourceString = @SourceString

WHILE len(@NewSourceString) >= @LengthOfTargetWord
BEGIN

    SET @PatternStartsAtPosition = CHARINDEX 
(@TargetWord,@NewSourceString)

    IF @PatternStartsAtPosition <> 0
    BEGIN
        SET @NumTimesRepeated = @NumTimesRepeated + 1

        SET @CurrentStringPosition = @CurrentStringPosition + @PatternStartsAtPosition + 
@LengthOfTargetWord

        SET @NewSourceString = substring(@NewSourceString,
 @PatternStartsAtPosition + 
@LengthOfTargetWord, @LengthOfString)

    END
    ELSE
    BEGIN
        SET @NewSourceString = ''
    END

END

RETURN @NumTimesRepeated
END

然后您可以通过以下方式使用它:

DECLARE @link varchar(max)='http://YourLinkHere.com'
SELECT SUM(dbo.WordRepeatedNumTimes(field, @link))
FROM Table

可以找到原始文章here