我有这张表,用于存储员工的请假余额。该表的结构如下。
CREATE TABLE [dbo].[tbl_EmployeeLeaveBalance](
[ID] [bigint] NOT NULL,
[EmpCode] [bigint] NOT NULL,
[FiscalYearCode] [smallint] NOT NULL,
[IsYearlyOpeningBalance] [bit] NULL,
[LeaveTypeCode] [tinyint] NULL,
[NoOfLeaves] [numeric](18, 2) NULL,
[Remarks] [nvarchar](2040) NULL
)
我想根据去年剩余的假期余额来计算新年度的余额。例如,如果某个雇员在本会计年度12
期间有权获得1
假,而他消费10
,那么当2
会计年度的余额将被修订时,2
叶子将被添加到明年的余额中。
IsYearlyOpeningBalance
字段将确定上一年的余额。基本上,对于1名雇员,他的1
休假类型2
行将被插入1(True
)行,因为雇员消耗休假,而1(False
)行则不会。
因此,行IsYearlyOpeningBalance = False
的余额将添加到下一行。目的是在需要时找出各自雇员各自年份的余额。
我已编写了此过程,但不适用于表的第一行和第二行,依此类推。
CREATE PROCEDURE [dbo].[ProcGetLeaveYearEndBalance]
(
@EmpCode bigint,
@LeaveType tinyint,
@FiscalYear smallint,
@Balance int
)
AS
BEGIN
INSERT INTO [tbl_EmployeeLeaveBalance] VALUES ((SELECT ISNULL(MAX(ID),0) FROM [tbl_EmployeeLeaveBalance])+1, @EmpCode, @FiscalYear, 1, @LeaveType,
(@Balance+ISNULL((SELECT TOP 1
ISNULL(LEAD(ISNULL(NULLIF(NoOfLeaves, 0), 0))OVER (PARTITION BY EmpCode, LeaveTypeCode ORDER BY [ID]), 0) [Previous]
FROM [tbl_EmployeeLeaveBalance]
WHERE IsYearlyOpeningBalance = 0 AND @EmpCode = EmpCode
ORDER BY [Previous] DESC),0)), 'Test')
INSERT INTO [tbl_EmployeeLeaveBalance] VALUES ((SELECT ISNULL(MAX(ID),0) FROM [tbl_EmployeeLeaveBalance])+1, @EmpCode, @FiscalYear, 0, @LeaveType,
(@Balance+ISNULL((SELECT TOP 1
ISNULL(LEAD(ISNULL(NULLIF(NoOfLeaves, 0), 0))OVER (PARTITION BY EmpCode, LeaveTypeCode ORDER BY [ID]), 0) [Previous]
FROM [tbl_EmployeeLeaveBalance]
WHERE IsYearlyOpeningBalance = 0 AND @EmpCode = EmpCode
ORDER BY [Previous] DESC),0)), 'Test')
END