if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PageViews_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PageViews_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE      PROCEDURE [dbo].cs_PageViews_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
	,@Paged BIT
)

AS
BEGIN

-- declare @Paged BIT
-- set @Paged = 1
-- declare @EndReportDate DateTime
-- set @EndReportDate = '1/1/2008'
-- declare @BegReportDate DateTime
-- set @BegReportDate = '1/1/1900'
-- declare @nRecordNumberStart INT
-- set @nRecordNumberStart = 1
-- declare @nRecordNumberEnd INT
-- set @nRecordNumberEnd = 100

IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
		--------------------------------------------------------------------
		-- Define the table to do the filtering and paging
		--------------------------------------------------------------------
		DECLARE @tblTempData TABLE
		(
			nID INT IDENTITY
			,URL varchar(512)
			,VisitCount INT
		)
		INSERT INTO @tblTempData
		(
			URL
			,VisitCount
		)
		SELECT
			URL, SUM(VisitCount) AS VisitCount
		FROM
			cs_PageViews AS PageViews
		WHERE 
			PageViews.DateTimeStamp between @BegReportDate and @EndReportDate
                GROUP BY
			URL
		ORDER BY
			VisitCount DESC
		SET @totalRecords = @@rowcount
		-------------------------------------------------------------------------------------
		
		SELECT
			URL
			,VisitCount
		FROM
			@tblTempData 
		WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
		ORDER BY 
			nID ASC
		
		--Return Record Count
		SELECT @totalRecords
	END
ELSE
	BEGIN
		SELECT
			URL, SUM(VisitCount) AS VisitCount
		FROM
			cs_PageViews AS PageViews
		WHERE 
			PageViews.DateTimeStamp between @BegReportDate and @EndReportDate
                GROUP BY
			URL
		ORDER BY
			VisitCount DESC
	END
END                                                                                                                                                                                                                               


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PageViews_Get] to public
go
