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

SET @SQLStatement = 'SELECT DISTINCT [c-ip] AS [Client IP], CASE WHEN 
  URIQuery.[cs-uri-query] IS NULL THEN URIStem.[cs-uri-stem] ELSE 
  URIStem.[cs-uri-stem] + ''?'' + URIQuery.[cs-uri-query] END AS [URL], 
  a.[sc-status] AS [Result Code] FROM vw_' + @TableName + ' a INNER JOIN 
  URIStem ON a.[cs-uri-stem] = URIStem.[ID] LEFT JOIN URIQuery ON 
  a.[cs-uri-query] = URIQuery.[ID] WHERE a.[sc-status] >= 400 AND 
  (CASE WHEN URIQuery.[cs-uri-query] IS NULL THEN URIStem.[cs-uri-stem] 
  ELSE URIStem.[cs-uri-stem] + ''?'' + URIQuery.[cs-uri-query] END) LIKE 
  ''%.exe'' OR (CASE WHEN URIQuery.[cs-uri-query] IS NULL THEN 
  URIStem.[cs-uri-stem] ELSE URIStem.[cs-uri-stem] + ''?'' + 
  URIQuery.[cs-uri-query] END) LIKE ''%.exe?%'' OR (CASE WHEN 
  URIQuery.[cs-uri-query] IS NULL THEN URIStem.[cs-uri-stem] ELSE 
  URIStem.[cs-uri-stem] + ''?'' + URIQuery.[cs-uri-query] END) LIKE 
  ''%.dll'' OR (CASE WHEN URIQuery.[cs-uri-query] IS NULL THEN 
  URIStem.[cs-uri-stem] ELSE URIStem.[cs-uri-stem] + ''?'' + 
  URIQuery.[cs-uri-query] END) LIKE ''%.dll?%'' OR (CASE WHEN 
  URIQuery.[cs-uri-query] IS NULL THEN URIStem.[cs-uri-stem] ELSE 
  URIStem.[cs-uri-stem] + ''?'' + URIQuery.[cs-uri-query] END) LIKE 
  ''%.ida'' OR (CASE WHEN URIQuery.[cs-uri-query] IS NULL THEN 
  URIStem.[cs-uri-stem] ELSE URIStem.[cs-uri-stem] + ''?'' + 
  URIQuery.[cs-uri-query] END) LIKE ''%.ida?%'' OR (CASE WHEN 
  URIQuery.[cs-uri-query] IS NULL THEN URIStem.[cs-uri-stem] ELSE 
  URIStem.[cs-uri-stem] + ''?'' + URIQuery.[cs-uri-query] END) LIKE 
  ''%.bat'' OR (CASE WHEN URIQuery.[cs-uri-query] IS NULL THEN 
  URIStem.[cs-uri-stem] ELSE URIStem.[cs-uri-stem] + ''?'' + 
  URIQuery.[cs-uri-query] END) LIKE ''%.bat?%'' OR (CASE WHEN 
  URIQuery.[cs-uri-query] IS NULL THEN URIStem.[cs-uri-stem] ELSE 
  URIStem.[cs-uri-stem] + ''?'' + URIQuery.[cs-uri-query] END) LIKE 
  ''%.com'' OR (CASE WHEN URIQuery.[cs-uri-query] IS NULL THEN 
  URIStem.[cs-uri-stem] ELSE URIStem.[cs-uri-stem] + ''?'' + 
  URIQuery.[cs-uri-query] END) LIKE ''%.com?%'' OR (CASE WHEN 
  URIQuery.[cs-uri-query] IS NULL THEN URIStem.[cs-uri-stem] ELSE 
  URIStem.[cs-uri-stem] + ''?'' + URIQuery.[cs-uri-query] END) LIKE 
  ''%.bat'' OR (CASE WHEN URIQuery.[cs-uri-query] IS NULL THEN 
  URIStem.[cs-uri-stem] ELSE URIStem.[cs-uri-stem] + ''?'' + 
  URIQuery.[cs-uri-query] END) LIKE ''%.bat?%'' AND a.[date-time] 
  BETWEEN CONVERT(datetime, @StartDate) AND CONVERT(datetime, @EndDate)
  ORDER BY [sc-status], [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
