CREATE PROCEDURE PageHitsByFrequency (
  @TableName nvarchar(25),
  @StartDate datetime = NULL,
  @EndDate datetime = NULL
) AS 
DECLARE @SQLStatement nvarchar(2000)
DECLARE @ParamDefs nvarchar(2000)

SET @SQLStatement = 'SELECT DISTINCT URIStem.[cs-uri-stem] AS 
  [Request URL], COUNT(URIStem.[cs-uri-stem]) AS Hits, 
  CONVERT(nvarchar(10), CONVERT(decimal(5, 3), (CONVERT(
  decimal(24, 4), COUNT(URIStem.[cs-uri-stem])) / CONVERT(
  decimal(24, 4), (SELECT SUM(a.Hits) AS Total FROM (SELECT 
  DISTINCT URIStem.[cs-uri-stem], COUNT(URIStem.[cs-uri-stem]) 
  AS [Hits] FROM vw_' + @TableName + ' a INNER JOIN URIStem ON
  a.[cs-uri-stem] = URIStem.[ID] WHERE a.[date-time] BETWEEN 
  CONVERT(datetime, @StartDate) AND CONVERT(datetime, @EndDate) 
  GROUP BY URIStem.[cs-uri-stem]) AS a)) * 100))) + ''%'' AS 
  [Percentage of Hits] FROM vw_' + @TableName + ' a INNER JOIN 
  URIStem ON a.[cs-uri-stem] = URIStem.[ID] WHERE a.[date-time] 
  BETWEEN CONVERT(datetime, @StartDate) AND CONVERT(datetime, 
  @EndDate) GROUP BY URIStem.[cs-uri-stem] HAVING CONVERT(
  decimal(5, 3), (CONVERT(decimal(24, 4), COUNT(
  URIStem.[cs-uri-stem])) / CONVERT(decimal(24, 4), (SELECT 
  SUM(a.Hits) AS Total FROM (SELECT DISTINCT URIStem.[cs-uri-stem] 
  AS [Page Request], COUNT(URIStem.[cs-uri-stem]) AS [Hits] FROM 
  vw_' + @TableName + ' a INNER JOIN URIStem ON a.[cs-uri-stem] = 
  URIStem.[ID] WHERE a.[date-time] BETWEEN CONVERT(datetime, 
  @StartDate) AND CONVERT(datetime, @EndDate) GROUP BY 
  URIStem.[cs-uri-stem]) AS a)) * 100)) > 1 ORDER BY 
  URIStem.[cs-uri-stem]'

SET @ParamDefs = '@StartDate datetime, @EndDate datetime'

IF (@StartDate IS NULL) SET @StartDate = CONVERT(datetime, '1/1/1753')
IF (@EndDate IS NULL) SET @EndDate = CONVERT(datetime, 
  '12/31/9999 11:59:59')

EXECUTE sp_executesql @SQLStatement, @ParamDefs, @StartDate, @EndDate
