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

SET @SQLStatement = 'SELECT DISTINCT UserAgent.[cs(User-Agent)] AS 
  [User Agent / Browser Type], COUNT(UserAgent.[cs(User-Agent)]) AS 
  Hits, CONVERT(nvarchar(10), CONVERT(decimal(5, 3), CONVERT(
  decimal(24, 4), COUNT(UserAgent.[cs(User-Agent)])) / CONVERT(
  decimal(24, 4), (SELECT SUM(a.Hits) AS Total FROM (SELECT DISTINCT
  UserAgent.[cs(User-Agent)] AS [User Agent / Browser Type], COUNT(
  UserAgent.[cs(User-Agent)]) AS [Hits] FROM vw_' + @TableName + ' i LEFT
  JOIN UserAgent ON i.[cs(User-Agent)] = UserAgent.[ID] WHERE 
  i.[date-time] BETWEEN CONVERT(datetime, @StartDate) AND CONVERT(
  datetime, @EndDate) AND NOT i.[cs(User-Agent)] IS NULL GROUP BY
  UserAgent.[cs(User-Agent)]) AS a)) * 100)) + ''%'' AS Percentage
  FROM vw_' + @TableName + ' a LEFT JOIN UserAgent ON a.[cs(User-Agent)]
  = UserAgent.[ID] WHERE a.[cs(User-Agent)] IS NOT NULL AND a.[date-time]
  BETWEEN CONVERT(datetime, @StartDate) AND CONVERT(datetime, @EndDate)
  GROUP BY UserAgent.[cs(User-Agent)] ORDER BY UserAgent.[cs(User-Agent)]'
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
