ALTER PROCEDURE [dbo].[sp_sales_in_period]
(@month_id int)
AS
declare @t table(id int identity(1,1) primary key, MonthID int, EmployeeID int, Employee nvarchar(50), Sales float, DateEntered datetime)
declare @employee_id int
declare cur cursor fast_forward read_only for (select EmployeeID from vSalesEmployeeList)
declare @max int
set @max = 13
set @month_id = @month_id-3
open cur
fetch next from cur into @employee_id
while @@fetch_status = 0
begin
set @month_id = @month_id+1
while @month_id <= @month_id + @max
begin
insert @t
SELECT
a.MonthID,
e.EmployeeID,
e.Employee,
ISNULL(a.Actual, 0) AS Sales,
a.DateEntered
FROM dbo.tblSales AS a INNER JOIN
dbo.vSalesEmployeeList AS e ON a.EmployeeID = e.EmployeeID
WHERE (a.MonthID = @month_id)
AND (a.EmployeeID = @employee_id)
AND (
a.DateEntered =
(SELECT MAX(DateEntered) AS Expr1 FROM dbo.tblSales as p WHERE (p.MonthID = @month_id) AND (p.EmployeeID = @employee_id))
)
ORDER BY a.MonthID, a.DateEntered
end
fetch next from cur into @employee_id
end
close cur
deallocate cur
begin select MonthID, EmployeeID, Employee, Sales, DateEntered from @t order by MonthID, Employee end
|