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

SET @SQLStatement = 'SELECT DISTINCT [c-ip] AS [Client IP], CONVERT(
  nvarchar(512), NULL) AS [Client Domain], COUNT([c-ip]) AS Hits, 
  CONVERT(nvarchar(10), CONVERT(decimal(5, 3), (CONVERT(decimal(24, 4),
  COUNT([c-ip])) / CONVERT(decimal(24, 4), (SELECT SUM(a.Hits) AS Total
  FROM (SELECT DISTINCT [c-ip] AS [Client IP], COUNT([c-ip]) AS [Hits]
  FROM vw_' + @TableName + ' a WHERE a.[date-time] BETWEEN CONVERT(
  datetime, @StartDate) AND CONVERT(datetime, @EndDate) AND NOT 
  a.[c-ip] IS NULL GROUP BY [c-ip]) AS a)) * 100))) + ''%'' AS 
  [Percentage] FROM vw_' + @TableName + ' WHERE [date-time] BETWEEN 
  CONVERT(datetime, @StartDate) AND CONVERT(datetime, @EndDate) AND 
  NOT [c-ip] IS NULL GROUP BY [c-ip] ORDER BY [c-ip]'
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
