USE [Content_NPD_COMM]
CREATE FUNCTION dbo.FindPatternLocation
(
@string NVARCHAR(MAX),
@term NVARCHAR(255)
)
RETURNS TABLE
AS
RETURN
(
SELECT pos = Number - LEN(@term)
FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(@string, Number,
CHARINDEX(@term, @string + @term, Number) - Number)))
FROM (SELECT ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects) AS n(Number)
WHERE Number > 1 AND Number <= CONVERT(INT, LEN(@string))
AND SUBSTRING(@term + @string, Number, LEN(@term)) = @term
) AS y);
DECLARE @ModuleID tinyint = 99
DECLARE @ID int = 420282034
DECLARE @MinBID bigint, @MaxBID bigint
SELECT
@MinBID = MIN([BacklinkID]),
@MaxBID = MAX([BacklinkID])
FROM [Content_NPD_COMM].[dbo].[BacklinkPhrase]
WHERE ModuleID = @ModuleID AND ID = @ID
SELECT COUNT(*)
FROM [dbo].[BacklinkComment]
CROSS APPLY dbo.FindPatternLocation([Comment], 'sp://num=')
WHERE BacklinkID BETWEEN @MinBID AND @MaxBID
SELECT COUNT(*)
FROM [dbo].[DocIntLnk]
WHERE ModuleFrom = @ModuleID AND IDFrom = @ID